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

export async function GET(
  _request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const route = getRoute(params.id);
    if (!route) {
      return NextResponse.json({ error: 'Route not found' }, { status: 404 });
    }
    return NextResponse.json(route);
  } catch (err) {
    console.error('Failed to fetch route:', err);
    return NextResponse.json({ error: 'Failed to fetch route' }, { status: 500 });
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const route = getRoute(params.id);
    if (!route) {
      return NextResponse.json({ error: 'Route not found' }, { status: 404 });
    }

    const body = await request.json();
    const db = getDb();

    const allowedFields = [
      'greeting_message',
      'after_hours_reply',
      'business_hours_json',
      'max_concurrent',
      'active',
      'bot_name',
      'closebot_bot_id',
      'closebot_source_id',
    ];

    const updates: string[] = [];
    const values: unknown[] = [];

    for (const field of allowedFields) {
      if (field in body) {
        updates.push(`${field} = ?`);
        // business_hours_json might come as object, stringify it
        if (field === 'business_hours_json' && typeof body[field] === 'object') {
          values.push(JSON.stringify(body[field]));
        } else {
          values.push(body[field]);
        }
      }
    }

    if (updates.length === 0) {
      return NextResponse.json({ error: 'No valid fields to update' }, { status: 400 });
    }

    updates.push("updated_at = datetime('now')");
    values.push(params.id);

    db.prepare(`UPDATE routes SET ${updates.join(', ')} WHERE id = ?`).run(...values);

    const updated = db.prepare('SELECT * FROM routes WHERE id = ?').get(params.id);
    return NextResponse.json(updated);
  } catch (err) {
    console.error('Failed to update route:', err);
    return NextResponse.json({ error: 'Failed to update route' }, { status: 500 });
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const route = getRoute(params.id);
    if (!route) {
      return NextResponse.json({ error: 'Route not found' }, { status: 404 });
    }

    const db = getDb();

    // Unassign contacts from this route
    db.prepare('UPDATE contacts SET assigned_route_id = NULL WHERE assigned_route_id = ?').run(params.id);

    // Delete the route
    db.prepare('DELETE FROM routes WHERE id = ?').run(params.id);

    return NextResponse.json({ success: true, id: params.id });
  } catch (err) {
    console.error('Failed to delete route:', err);
    return NextResponse.json({ error: 'Failed to delete route' }, { status: 500 });
  }
}
