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

/** Shape returned to the frontend for each bot */
export interface BotListItem {
  id: string;
  name: string;
  category: string;
  active: boolean;
  locked: boolean;
  favorited: boolean;
  twilioNumber: string | null;
  routeId: string | null;
  sourceIds: string[];
  sourceNames: string[];
  modifiedAt: string;
  /* metrics – filled when available */
  messageCount: number;
  conversionPct: number | null;
  lastActive: string | null;
  publishedVersions: number;
  totalVersions: number;
}

// ---------------------------------------------------------------------------
// Mock data when CloseBot API is unavailable
// ---------------------------------------------------------------------------
function mockBots(): BotListItem[] {
  const now = new Date().toISOString();
  return [
    {
      id: 'mock-1',
      name: 'Sales Closer',
      category: 'sales',
      active: true,
      locked: false,
      favorited: true,
      twilioNumber: '+18005551234',
      routeId: null,
      sourceIds: ['src-1', 'src-2'],
      sourceNames: ['Website Chat', 'Facebook Ads'],
      modifiedAt: now,
      messageCount: 1842,
      conversionPct: 34.2,
      lastActive: new Date(Date.now() - 12 * 60000).toISOString(),
      publishedVersions: 2,
      totalVersions: 5,
    },
    {
      id: 'mock-2',
      name: 'Appointment Setter',
      category: 'scheduling',
      active: true,
      locked: false,
      favorited: false,
      twilioNumber: '+18005555678',
      routeId: null,
      sourceIds: ['src-3'],
      sourceNames: ['Google Ads'],
      modifiedAt: now,
      messageCount: 956,
      conversionPct: 48.7,
      lastActive: new Date(Date.now() - 3 * 3600000).toISOString(),
      publishedVersions: 1,
      totalVersions: 3,
    },
    {
      id: 'mock-3',
      name: 'Lead Qualifier',
      category: 'qualification',
      active: true,
      locked: false,
      favorited: false,
      twilioNumber: null,
      routeId: null,
      sourceIds: ['src-1'],
      sourceNames: ['Website Chat'],
      modifiedAt: now,
      messageCount: 2310,
      conversionPct: 22.1,
      lastActive: new Date(Date.now() - 45 * 60000).toISOString(),
      publishedVersions: 1,
      totalVersions: 2,
    },
    {
      id: 'mock-4',
      name: 'Follow-Up Bot',
      category: 'nurture',
      active: false,
      locked: false,
      favorited: false,
      twilioNumber: '+18005559012',
      routeId: null,
      sourceIds: [],
      sourceNames: [],
      modifiedAt: now,
      messageCount: 412,
      conversionPct: 12.5,
      lastActive: new Date(Date.now() - 3 * 86400000).toISOString(),
      publishedVersions: 0,
      totalVersions: 1,
    },
    {
      id: 'mock-5',
      name: 'Review Collector',
      category: 'reviews',
      active: true,
      locked: false,
      favorited: true,
      twilioNumber: null,
      routeId: null,
      sourceIds: ['src-4'],
      sourceNames: ['SMS Blast'],
      modifiedAt: now,
      messageCount: 687,
      conversionPct: 61.3,
      lastActive: new Date(Date.now() - 6 * 3600000).toISOString(),
      publishedVersions: 1,
      totalVersions: 4,
    },
  ];
}

// ---------------------------------------------------------------------------
// GET /api/bots
// ---------------------------------------------------------------------------
export async function GET() {
  const cb = getCloseBotClient();

  // Build a map of botId → route for Twilio number look-ups
  let routeMap: Record<string, { twilioNumber: string; routeId: string }> = {};
  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) {
        routeMap[r.closebot_bot_id] = {
          twilioNumber: r.twilio_number,
          routeId: r.id,
        };
      }
    }
  } catch {
    // DB may not be initialised yet – continue without routes
  }

  // Try fetching from CloseBot
  if (cb.isConfigured) {
    try {
      const [rawBots, summary] = await Promise.all([
        cb.listBots(),
        cb.getAgencySummary().catch(() => null),
      ]);

      // Parse optional summary metrics keyed by bot id
      const metricsMap: Record<string, { messageCount: number; conversionPct: number | null }> = {};
      if (summary && Array.isArray((summary as any).bots)) {
        for (const b of (summary as any).bots) {
          metricsMap[b.id] = {
            messageCount: b.totalMessages ?? 0,
            conversionPct: b.conversionRate ?? null,
          };
        }
      }

      const bots: BotListItem[] = rawBots.map((b) => {
        const route = routeMap[b.id];
        const metrics = metricsMap[b.id];
        const hasPublished = b.versions?.some((v) => v.published) ?? false;
        const publishedVersions = b.versions?.filter((v) => v.published).length ?? 0;
        const totalVersions = b.versions?.length ?? 0;

        return {
          id: b.id,
          name: b.name,
          category: b.category || 'general',
          active: hasPublished && !b.locked,
          locked: b.locked,
          favorited: b.favorited,
          twilioNumber: route?.twilioNumber ?? null,
          routeId: route?.routeId ?? null,
          sourceIds: b.sources?.map((s) => s.id) ?? [],
          sourceNames: b.sources?.map((s) => s.name) ?? [],
          modifiedAt: b.modifiedAt,
          messageCount: metrics?.messageCount ?? 0,
          conversionPct: metrics?.conversionPct ?? null,
          lastActive: b.modifiedAt,
          publishedVersions,
          totalVersions,
        };
      });

      return NextResponse.json({ bots, mock: false });
    } catch (err) {
      console.error('[api/bots] CloseBot API error, falling back to mock:', err);
    }
  }

  // Fallback → mock data
  const bots = mockBots();
  // merge any real routes into mock
  return NextResponse.json({ bots, mock: true });
}
