import { NextResponse } from 'next/server';
import type { Request } from 'next/server';

export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { host, port, username, password, apiUrl } = body;

    if (!host || !port) {
      return NextResponse.json({ success: false, error: 'Host and port are required' }, { status: 400 });
    }

    const endpoint = apiUrl || `http://${host}:${port}`;

    // Test connection to SMS Gateway app
    // The app exposes a health or info endpoint with Basic Auth
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout

    try {
      const headers: HeadersInit = {
        'Authorization': `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
      };

      // Try /health or /info endpoint first
      const healthRes = await fetch(`${endpoint}/health`, {
        method: 'GET',
        headers,
        signal: timeoutId.signal,
      }).catch(() => null);

      // Fallback to root endpoint
      const rootRes = await fetch(endpoint, {
        method: 'GET',
        headers,
        signal: timeoutId.signal,
      });

      if (healthRes?.ok || rootRes?.ok) {
        return NextResponse.json({
          success: true,
          deviceInfo: {
            model: 'SMS Gateway for Android',
            endpoint,
          },
        });
      }

      return NextResponse.json({ success: false, error: 'Unable to connect. Check IP, port, and credentials.' });
    } catch (error: any) {
      clearTimeout(timeoutId);
      return NextResponse.json(
        { success: false, error: error.message || 'Connection failed' },
        { status: 200 }
      );
    }
  }
}
