import type { APIRoute } from 'astro';
import { TerritoryManagerAuth } from '../../../lib/territory-manager-auth';
import { territoryManagerAPI } from '../../../lib/territory-manager-api';

export const GET: APIRoute = async ({ request: _request }) => {
  try {
    // Check if user is authenticated as territory manager
    const territoryManager = await TerritoryManagerAuth.getCurrentTerritoryManager();
    if (!territoryManager) {
      return new Response(JSON.stringify({ error: 'Not authenticated as territory manager' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Load dashboard data
    const [
      stats,
      leads,
      commissions,
      achievements,
      notifications,
      territories
    ] = await Promise.all([
      territoryManagerAPI.getTerritoryManagerStats(territoryManager.id),
      territoryManagerAPI.getLeads(territoryManager.id),
      territoryManagerAPI.getCommissions(territoryManager.id),
      territoryManagerAPI.getAchievements(),
      territoryManagerAPI.getNotifications(territoryManager.id),
      territoryManagerAPI.getTerritories()
    ]);

    // Get territory info
    const territory = territories.find(t => t.id === territoryManager.territory_id);

    // Generate recent activity
    const recentActivity = [
      ...commissions.slice(0, 3).map(c => ({
        type: 'commission',
        message: `Earned $${c.total_commission} commission`,
        created_at: c.created_at
      })),
      ...leads.slice(0, 2).map(l => ({
        type: 'lead',
        message: `${l.status === 'converted' ? 'Converted' : 'Added'} lead: ${l.event_name}`,
        created_at: l.created_at
      }))
    ].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());

    // Generate earnings history from commissions
    const earningsHistory = generateEarningsHistory(commissions);

    // Filter for active leads
    const activeLeads = leads.filter(l => l.status !== 'converted' && l.status !== 'dead');

    const dashboardData = {
      territoryManager,
      territory,
      profile: territoryManager.profile,
      stats,
      recent_activity: recentActivity,
      active_leads: activeLeads,
      achievements,
      notifications,
      earnings_history: earningsHistory
    };

    return new Response(JSON.stringify(dashboardData), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (_error) {
    console.error('Territory manager dashboard error:', _error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

function generateEarningsHistory(commissions: Array<{created_at: string; total_commission: number}>): Array<{month: string; earnings: number}> {
  const monthlyEarnings = new Map<string, number>();
  
  commissions.forEach(commission => {
    const month = commission.created_at.substring(0, 7); // YYYY-MM
    const current = monthlyEarnings.get(month) || 0;
    monthlyEarnings.set(month, current + commission.total_commission);
  });

  return Array.from(monthlyEarnings.entries())
    .map(([month, amount]) => ({
      date: month + '-01',
      amount
    }))
    .sort((a, b) => a.date.localeCompare(b.date));
}