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

export const dynamic = 'force-dynamic';

interface AgencySummary {
  currentMonthMessageCount?: number;
  lastMonthMessageCount?: number;
  currentMonthSuccessfulBookings?: number;
  currentMonthContacts?: number;
  lastMonthContacts?: number;
  currentMonthActiveSources?: number;
}

export async function GET() {
  // Start with local DB stats
  let localStats = { activeConversations: 0, messagesToday: 0 };
  try {
    const raw = getStats();
    localStats = {
      activeConversations: raw.activeConversations?.c ?? 0,
      messagesToday: raw.messagesToday?.c ?? 0,
    };
  } catch (error) {
    console.error('[stats] Failed to get local DB stats:', error);
  }

  // Try to enrich with CloseBot API data
  let cbStats: AgencySummary | null = null;
  try {
    const cb = getCloseBotClient();
    if (cb.isConfigured) {
      cbStats = await cb.getAgencySummary() as AgencySummary;
    }
  } catch (error) {
    console.error('[stats] Failed to fetch CloseBot agency summary:', error);
  }

  // Merge: prefer CloseBot data when available; fall back to local
  const activeConversations =
    (cbStats?.currentMonthContacts ?? 0) > 0
      ? cbStats!.currentMonthContacts!
      : localStats.activeConversations;

  const messagesToday =
    (cbStats?.currentMonthMessageCount ?? 0) > 0
      ? cbStats!.currentMonthMessageCount!
      : localStats.messagesToday;

  const bookingsMade = cbStats?.currentMonthSuccessfulBookings ?? 0;

  // Calculate response rate: if we have last month contacts, compute growth; otherwise show a derived metric
  let responseRate = 0;
  if (cbStats) {
    const contacts = cbStats.currentMonthContacts ?? 0;
    const messages = cbStats.currentMonthMessageCount ?? 0;
    if (contacts > 0 && messages > 0) {
      // Use messages-per-contact as a proxy for engagement, capped at 100
      responseRate = Math.min(Math.round((messages / contacts) * 10), 100);
    }
  }

  const stats = {
    activeConversations,
    messagesToday,
    bookingsMade,
    responseRate,
  };

  return NextResponse.json(stats);
}
