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

export const dynamic = 'force-dynamic';

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

export async function GET() {
  const cb = getCloseBotClient();

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

  try {
    const summary = await cb.getAgencySummary() as AgencySummary;

    return NextResponse.json({
      currentMonthMessageCount: summary.currentMonthMessageCount ?? 0,
      lastMonthMessageCount: summary.lastMonthMessageCount ?? 0,
      totalStorage: summary.totalStorage ?? 0,
      currentMonthSuccessfulBookings: summary.currentMonthSuccessfulBookings ?? 0,
      currentMonthActiveSources: summary.currentMonthActiveSources ?? 0,
      currentMonthContacts: summary.currentMonthContacts ?? 0,
      lastMonthContacts: summary.lastMonthContacts ?? 0,
    });
  } catch (error) {
    console.error('[closebot-stats] Failed to fetch agency summary:', error);
    return NextResponse.json(
      { error: 'Failed to fetch CloseBot stats' },
      { status: 500 }
    );
  }
}
