import { NextRequest, NextResponse } from 'next/server';
import { getContact, insertMessage, getRoute } from '@/lib/db';
import { generateId } from '@/lib/utils';

export async function POST(
  req: NextRequest,
  { params }: { params: { contactId: string } }
) {
  try {
    const { contactId } = params;
    const body = await req.json();
    const messageText: string = body.message?.trim();

    if (!messageText) {
      return NextResponse.json({ error: 'Message is required' }, { status: 400 });
    }

    // Get the contact
    const contact = getContact(contactId) as {
      id: string;
      phone: string;
      assigned_route_id: string | null;
    } | undefined;

    if (!contact) {
      return NextResponse.json({ error: 'Contact not found' }, { status: 404 });
    }

    // Try to send via Twilio
    let twilioSid: string | undefined;
    if (contact.assigned_route_id) {
      const route = getRoute(contact.assigned_route_id) as {
        twilio_number: string;
      } | undefined;

      if (route) {
        try {
          const { sendSms } = await import('@/lib/twilio-client');
          twilioSid = await sendSms(contact.phone, route.twilio_number, messageText);
        } catch (err) {
          // Twilio not configured — log but don't fail
          console.warn('Twilio send skipped (no credentials):', (err as Error).message);
        }
      }
    }

    // Log message to DB regardless
    const messageId = generateId();
    insertMessage({
      id: messageId,
      contact_id: contactId,
      route_id: contact.assigned_route_id || undefined,
      direction: 'outbound',
      source: 'manual',
      body: messageText,
      twilio_sid: twilioSid,
    });

    return NextResponse.json({
      ok: true,
      messageId,
      twilioSid: twilioSid || null,
      delivered: !!twilioSid,
    });
  } catch (err) {
    console.error('POST /api/conversations/[contactId]/send error:', err);
    return NextResponse.json({ error: 'Failed to send message' }, { status: 500 });
  }
}
