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, to, message } = body;

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

    if (!username || !password) {
      return NextResponse.json(
        { success: false, error: 'Username and password are required for authentication' },
        { status: 400 }
      );
    }

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

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 15000); // 15s timeout

    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Authorization': `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message: message,
          phoneNumbers: [to],
        }),
        signal: timeoutId.signal,
      });

      clearTimeout(timeoutId);

      if (!res.ok) {
        const errorText = await res.text();
        return NextResponse.json(
          { success: false, error: errorText || 'Failed to send SMS' },
          { status: 200 }
        );
      }

      const data = await res.json();
      return NextResponse.json({
        success: true,
        messageId: data.id,
      });
    } catch (error: any) {
      clearTimeout(timeoutId);
      return NextResponse.json(
        { success: false, error: error.message || 'Failed to send SMS' },
        { status: 200 }
      );
    }
  }
}
