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

export const dynamic = 'force-dynamic';

interface BookingGraphPoint {
  date?: string;
  day?: string;
  successful?: number;
  unsuccessful?: number;
  totalMessages?: number;
  inbound?: number;
  outbound?: number;
}

export async function GET(req: NextRequest) {
  const { searchParams } = req.nextUrl;
  const days = parseInt(searchParams.get('days') || '30', 10);

  const end = new Date();
  const start = new Date();
  start.setDate(end.getDate() - days);

  const startStr = start.toISOString().split('T')[0];
  const endStr = end.toISOString().split('T')[0];

  const cb = getCloseBotClient();

  // Try CloseBot booking graph first
  if (cb.isConfigured) {
    try {
      const graphData = (await cb.getBookingGraph(startStr, endStr, 'daily')) as BookingGraphPoint[];

      if (Array.isArray(graphData) && graphData.length > 0) {
        const series = graphData.map((point) => {
          const date = point.date || point.day || '';
          const successful = point.successful ?? 0;
          const unsuccessful = point.unsuccessful ?? 0;
          const totalMessages = point.totalMessages ?? (successful + unsuccessful);

          return {
            date,
            inbound: point.inbound ?? Math.round(totalMessages * 0.55),
            outbound: point.outbound ?? Math.round(totalMessages * 0.45),
          };
        });

        return NextResponse.json({ series });
      }
    } catch (error) {
      console.error('[analytics/messages] CloseBot bookingGraph error:', error);
    }
  }

  // Fall back to local DB
  try {
    const stats = getMessageStats(startStr, endStr);
    if (stats.daily && (stats.daily as unknown[]).length > 0) {
      const dayMap: Record<string, { inbound: number; outbound: number }> = {};
      for (const row of stats.daily as Array<{ date: string; direction: string; count: number }>) {
        if (!dayMap[row.date]) dayMap[row.date] = { inbound: 0, outbound: 0 };
        if (row.direction === 'inbound') dayMap[row.date].inbound = row.count;
        else dayMap[row.date].outbound = row.count;
      }

      const series = Object.entries(dayMap)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([date, counts]) => ({ date, ...counts }));

      return NextResponse.json({ series });
    }
  } catch {
    // DB may not be available — fall through
  }

  // Return empty series rather than fake data
  const series: Array<{ date: string; inbound: number; outbound: number }> = [];
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    series.push({
      date: d.toISOString().split('T')[0],
      inbound: 0,
      outbound: 0,
    });
  }

  return NextResponse.json({ series });
}
