import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseAdmin } from '@/lib/supabase/server';
import { logger } from '@/lib/logger';

/**
 * GET /api/ceo/metrics
 * 
 * Comprehensive platform metrics for launch monitoring.
 * PIN-protected (no user auth required — accessed from CEO dashboard).
 */
export async function GET(request: NextRequest) {
  const pin = request.headers.get('x-ceo-pin');
  if (pin !== '5050') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const admin = getSupabaseAdmin();
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
    const last7d = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
    const last24h = new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString();
    const last30d = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();

    const [
      { count: totalWorkers },
      { count: totalContractors },
      { count: totalJobs },
      { count: activeJobs },
      { count: totalMatches },
      { count: hiredMatches },
      { count: totalPayments },
      { count: totalRatings },
      { count: totalFeedback },
      { count: newFeedback },
      { data: signups7d },
      { data: signups24h },
      { data: recentHires },
      { data: recentJobs },
      { count: pendingMatches },
      { data: paymentData },
      { data: allPayments },
      { data: recentHireDates },
      { data: profileLocations },
      { data: companyLocations },
    ] = await Promise.all([
      admin.from('profiles').select('*', { count: 'exact', head: true }).eq('type', 'worker'),
      admin.from('profiles').select('*', { count: 'exact', head: true }).eq('type', 'contractor'),
      admin.from('jobs').select('*', { count: 'exact', head: true }),
      admin.from('jobs').select('*', { count: 'exact', head: true }).eq('status', 'active'),
      admin.from('matches').select('*', { count: 'exact', head: true }),
      admin.from('matches').select('*', { count: 'exact', head: true }).eq('status', 'hired'),
      admin.from('payments').select('*', { count: 'exact', head: true }).eq('status', 'charged'),
      admin.from('ratings').select('*', { count: 'exact', head: true }),
      admin.from('feedback').select('*', { count: 'exact', head: true }),
      admin.from('feedback').select('*', { count: 'exact', head: true }).eq('status', 'new'),
      admin.from('profiles').select('type, created_at').gte('created_at', last7d).order('created_at', { ascending: false }),
      admin.from('profiles').select('type, created_at').gte('created_at', last24h),
      admin.from('matches').select('id, hired_at').eq('status', 'hired').gte('hired_at', last30d).order('hired_at', { ascending: false }).limit(10),
      admin.from('jobs').select('id, title, status, created_at').gte('created_at', last7d).order('created_at', { ascending: false }).limit(10),
      admin.from('matches').select('*', { count: 'exact', head: true }).in('status', ['applied', 'suggested']),
      admin.from('payments').select('amount, status').eq('status', 'charged'),
      // Payment stats (all statuses)
      admin.from('payments').select('amount, status, created_at'),
      // Hires with dates for daily revenue trend
      admin.from('matches').select('hired_at').eq('status', 'hired').not('hired_at', 'is', null).gte('hired_at', last7d),
      // Geographic data
      admin.from('profiles').select('suburb, type').not('suburb', 'is', null),
      admin.from('companies').select('address').not('address', 'is', null),
    ]);

    // Calculate revenue
    const revenue = (paymentData || []).reduce((sum, p) => sum + (p.amount || 0), 0);

    // Signup breakdown
    const signups7dList = signups7d || [];
    const signups24hList = signups24h || [];

    // Daily signup trend (last 7 days)
    const dailySignups: Record<string, { workers: number; contractors: number }> = {};
    for (let i = 0; i < 7; i++) {
      const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
      const key = d.toISOString().slice(0, 10);
      dailySignups[key] = { workers: 0, contractors: 0 };
    }
    for (const s of signups7dList) {
      const key = s.created_at.slice(0, 10);
      if (dailySignups[key]) {
        if (s.type === 'worker') dailySignups[key].workers++;
        else dailySignups[key].contractors++;
      }
    }

    // Funnel metrics
    const hireRate = (totalMatches || 0) > 0
      ? Math.round(((hiredMatches || 0) / (totalMatches || 1)) * 100)
      : 0;

    // Payment success rate
    const allPaymentsList = allPayments || [];
    const chargedPayments = allPaymentsList.filter(p => p.status === 'charged').length;
    const failedPayments = allPaymentsList.filter(p => p.status === 'failed').length;
    const totalAttempted = chargedPayments + failedPayments;
    const paymentSuccessRate = totalAttempted > 0
      ? Math.round((chargedPayments / totalAttempted) * 100)
      : 100;

    // Daily revenue trend (last 7 days)
    const dailyRevenue: Record<string, number> = {};
    for (let i = 0; i < 7; i++) {
      const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
      dailyRevenue[d.toISOString().slice(0, 10)] = 0;
    }
    for (const h of (recentHireDates || [])) {
      if (h.hired_at) {
        const day = h.hired_at.slice(0, 10);
        if (dailyRevenue[day] !== undefined) {
          dailyRevenue[day] += 50; // $50 per hire
        }
      }
    }

    const dailyRevenueTrend = Object.entries(dailyRevenue)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([date, amount]) => ({ date, amount, hires: amount / 50 }));

    // Geographic breakdown
    const AU_STATES = ['NSW', 'VIC', 'QLD', 'WA', 'SA', 'TAS', 'ACT', 'NT'];
    const locationCounts: Record<string, { workers: number; contractors: number }> = {};

    for (const p of (profileLocations || [])) {
      const suburb = (p.suburb || '').trim();
      if (!suburb) continue;
      const area = suburb.charAt(0).toUpperCase() + suburb.slice(1).toLowerCase();
      if (!locationCounts[area]) locationCounts[area] = { workers: 0, contractors: 0 };
      if (p.type === 'worker') locationCounts[area].workers++;
      else locationCounts[area].contractors++;
    }

    const stateCounts: Record<string, number> = {};
    for (const c of (companyLocations || [])) {
      const addr = (c.address || '').toUpperCase();
      const matchedState = AU_STATES.find(s => addr.includes(s));
      if (matchedState) {
        stateCounts[matchedState] = (stateCounts[matchedState] || 0) + 1;
      }
    }

    const topLocations = Object.entries(locationCounts)
      .map(([area, counts]) => ({ area, total: counts.workers + counts.contractors, ...counts }))
      .sort((a, b) => b.total - a.total)
      .slice(0, 15);

    const stateDistribution = Object.entries(stateCounts)
      .map(([state, count]) => ({ state, count }))
      .sort((a, b) => b.count - a.count);

    return NextResponse.json({
      timestamp: now.toISOString(),
      totals: {
        workers: totalWorkers || 0,
        contractors: totalContractors || 0,
        jobs: totalJobs || 0,
        activeJobs: activeJobs || 0,
        matches: totalMatches || 0,
        hires: hiredMatches || 0,
        payments: totalPayments || 0,
        ratings: totalRatings || 0,
        feedback: totalFeedback || 0,
        newFeedback: newFeedback || 0,
        pendingMatches: pendingMatches || 0,
      },
      revenue: {
        total: revenue,
        perHire: 50,
        currency: 'AUD',
        successRate: paymentSuccessRate,
        totalAttempted,
        dailyTrend: dailyRevenueTrend,
      },
      activity: {
        signups24h: {
          workers: signups24hList.filter(s => s.type === 'worker').length,
          contractors: signups24hList.filter(s => s.type === 'contractor').length,
          total: signups24hList.length,
        },
        signups7d: {
          workers: signups7dList.filter(s => s.type === 'worker').length,
          contractors: signups7dList.filter(s => s.type === 'contractor').length,
          total: signups7dList.length,
        },
        dailyTrend: Object.entries(dailySignups)
          .sort(([a], [b]) => a.localeCompare(b))
          .map(([date, counts]) => ({ date, ...counts })),
      },
      funnel: {
        hireRate,
        pendingMatches: pendingMatches || 0,
      },
      recent: {
        hires: (recentHires || []).map(h => ({ id: h.id, hiredAt: h.hired_at })),
        jobs: (recentJobs || []).map(j => ({ id: j.id, title: j.title, status: j.status, createdAt: j.created_at })),
      },
      geography: {
        topLocations,
        stateDistribution,
      },
    });
  } catch (error) {
    logger.error('CEO metrics error:', error);
    return NextResponse.json({ error: 'Failed to load metrics' }, { status: 500 });
  }
}
