import { NextResponse } from 'next/server';
import pool from '@/lib/db';
import { getSessionUser } from '@/lib/auth';

export async function GET() {
  try {
    const session = await getSessionUser();
    if (!session || session.role !== 'admin') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const [users, leads, buyers, matches, outreach, subscriptions] = await Promise.all([
      pool.query('SELECT count(*) as total, role FROM users GROUP BY role'),
      pool.query("SELECT count(*) as total FROM seller_leads"),
      pool.query("SELECT count(*) as total FROM buyers"),
      pool.query("SELECT count(*) as total, avg(match_score) as avg_score FROM matches"),
      pool.query("SELECT count(*) as total FROM outreach WHERE sent_at IS NOT NULL"),
      pool.query("SELECT count(*) as total FROM subscriptions WHERE status = 'active'"),
    ]);

    const userCounts: Record<string, number> = {};
    for (const row of users.rows) {
      userCounts[row.role] = parseInt(row.total);
    }

    return NextResponse.json({
      users: {
        total: Object.values(userCounts).reduce((a, b) => a + b, 0),
        admins: userCounts.admin || 0,
        agents: userCounts.agent || 0,
        buyers: userCounts.buyer || 0,
      },
      leads: parseInt(leads.rows[0].total),
      buyers_count: parseInt(buyers.rows[0].total),
      matches: {
        total: parseInt(matches.rows[0].total),
        avg_score: parseFloat(matches.rows[0].avg_score) || 0,
      },
      outreach_sent: parseInt(outreach.rows[0].total),
      active_subscriptions: parseInt(subscriptions.rows[0].total),
    });
  } catch (error) {
    console.error('Admin stats error:', error);
    return NextResponse.json({ error: 'Failed to fetch stats' }, { status: 500 });
  }
}
