import { NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { broadcast } from '@/lib/sse';

export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  try {
    const formData = await request.formData();
    const messageSid = (formData.get('MessageSid') as string) || '';
    const messageStatus = (formData.get('MessageStatus') as string) || '';

    if (!messageSid || !messageStatus) {
      console.warn('[status] Missing MessageSid or MessageStatus in callback');
      return new Response('', { status: 400 });
    }

    console.log(`[status] Twilio status update: ${messageSid} → ${messageStatus}`);

    const db = getDb();
    const result = db.prepare(
      'UPDATE messages SET twilio_status = ? WHERE twilio_sid = ?'
    ).run(messageStatus, messageSid);

    if (result.changes === 0) {
      console.warn(`[status] No message found with twilio_sid: ${messageSid}`);
    } else {
      // Fetch the updated message for SSE broadcast
      const msg = db.prepare(
        'SELECT id, contact_id, route_id, direction FROM messages WHERE twilio_sid = ?'
      ).get(messageSid) as { id: string; contact_id: string; route_id: string; direction: string } | undefined;

      if (msg) {
        broadcast('status', {
          message_id: msg.id,
          contact_id: msg.contact_id,
          twilio_sid: messageSid,
          status: messageStatus,
          updated_at: new Date().toISOString(),
        });
      }
    }

    // Handle delivery failures
    if (messageStatus === 'failed' || messageStatus === 'undelivered') {
      console.error(`[status] SMS delivery failed: ${messageSid} status=${messageStatus}`);

      const errorCode = formData.get('ErrorCode') as string;
      const errorMessage = formData.get('ErrorMessage') as string;
      if (errorCode || errorMessage) {
        console.error(`[status] Error details: code=${errorCode}, message=${errorMessage}`);
      }
    }

    return new Response('', { status: 200 });
  } catch (error) {
    console.error('[status] Unhandled error in status callback:', error);
    // Return 200 anyway to prevent Twilio retries
    return new Response('', { status: 200 });
  }
}
