import { NextResponse } from 'next/server';
import { testConnection as testTwilio } from '@/lib/twilio-client';
import { getCloseBotClient } from '@/lib/closebot';

export const dynamic = 'force-dynamic';

interface AgencyInfo {
  name?: string;
  companyName?: string;
  email?: string;
}

interface AgencySummary {
  currentMonthActiveSources?: number;
  currentMonthContacts?: number;
  currentMonthMessageCount?: number;
}

export async function POST() {
  const results: {
    twilio: boolean;
    closebot: boolean;
    closebotAgencyName?: string;
    closebotSourcesCount?: number;
  } = {
    twilio: false,
    closebot: false,
  };

  // Test Twilio
  try {
    results.twilio = await testTwilio();
  } catch (error) {
    console.error('[test-connection] Twilio test failed:', error);
    results.twilio = false;
  }

  // Test CloseBot — also fetch agency info
  try {
    const cb = getCloseBotClient();
    if (!cb.isConfigured) {
      results.closebot = false;
    } else {
      // Test by fetching agency current info
      try {
        const agencyInfo = (await cb.get('/agency/current')) as AgencyInfo;
        results.closebot = true;
        results.closebotAgencyName = agencyInfo.companyName || agencyInfo.name || 'Connected';
      } catch {
        results.closebot = false;
      }

      // If connected, also fetch sources count
      if (results.closebot) {
        try {
          const summary = (await cb.getAgencySummary()) as AgencySummary;
          results.closebotSourcesCount = summary.currentMonthActiveSources ?? 0;
        } catch {
          // Non-critical — just skip
        }
      }
    }
  } catch (error) {
    console.error('[test-connection] CloseBot test failed:', error);
    results.closebot = false;
  }

  return NextResponse.json(results);
}
