import { NextRequest, NextResponse } from 'next/server';
import { getDb, getRoutes } from '@/lib/db';
import { generateId } from '@/lib/utils';

export async function GET() {
  try {
    const routes = getRoutes();
    return NextResponse.json(routes);
  } catch (err) {
    console.error('Failed to fetch routes:', err);
    return NextResponse.json({ error: 'Failed to fetch routes' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { twilio_number, twilio_number_sid, closebot_source_id, closebot_bot_id, bot_name } = body;

    if (!twilio_number || !closebot_source_id) {
      return NextResponse.json(
        { error: 'twilio_number and closebot_source_id are required' },
        { status: 400 }
      );
    }

    const db = getDb();
    const id = generateId();

    db.prepare(`
      INSERT INTO routes (id, twilio_number, twilio_number_sid, closebot_source_id, closebot_bot_id, bot_name)
      VALUES (?, ?, ?, ?, ?, ?)
    `).run(id, twilio_number, twilio_number_sid || null, closebot_source_id, closebot_bot_id || null, bot_name || null);

    const route = db.prepare('SELECT * FROM routes WHERE id = ?').get(id);
    return NextResponse.json(route, { status: 201 });
  } catch (err: unknown) {
    console.error('Failed to create route:', err);
    const message = err instanceof Error ? err.message : 'Failed to create route';
    // Handle unique constraint on twilio_number
    if (message.includes('UNIQUE constraint')) {
      return NextResponse.json(
        { error: 'A route for this Twilio number already exists' },
        { status: 409 }
      );
    }
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
