import { NextRequest, NextResponse } from 'next/server';
import { getCloseBotClient } from '@/lib/closebot';
import { getRoutes } from '@/lib/db';

// ---------------------------------------------------------------------------
// GET /api/bots/[id]  — single bot detail + metrics
// ---------------------------------------------------------------------------
export async function GET(
  _req: NextRequest,
  { params }: { params: { id: string } }
) {
  const botId = params.id;
  const cb = getCloseBotClient();

  // Try route mapping
  let twilioNumber: string | null = null;
  let routeId: string | null = null;
  try {
    const routes = getRoutes() as Array<{
      id: string;
      twilio_number: string;
      closebot_bot_id: string | null;
    }>;
    for (const r of routes) {
      if (r.closebot_bot_id === botId) {
        twilioNumber = r.twilio_number;
        routeId = r.id;
        break;
      }
    }
  } catch {
    // DB may not exist yet
  }

  if (!cb.isConfigured) {
    return NextResponse.json(
      { error: 'CloseBot API key not configured', botId },
      { status: 503 }
    );
  }

  try {
    const [botDetail, summary] = await Promise.all([
      cb.getBot(botId),
      cb.getAgencySummary().catch(() => null),
    ]);

    // Extract metrics for this bot from agency summary
    let metrics: { messageCount: number; conversionPct: number | null } = {
      messageCount: 0,
      conversionPct: null,
    };
    if (summary && Array.isArray((summary as any).bots)) {
      const found = (summary as any).bots.find((b: any) => b.id === botId);
      if (found) {
        metrics = {
          messageCount: found.totalMessages ?? 0,
          conversionPct: found.conversionRate ?? null,
        };
      }
    }

    return NextResponse.json({
      ...(botDetail as object),
      twilioNumber,
      routeId,
      metrics,
    });
  } catch (err: any) {
    console.error(`[api/bots/${botId}] error:`, err);
    return NextResponse.json(
      { error: err.message || 'Failed to fetch bot', botId },
      { status: 502 }
    );
  }
}
