import { db } from '@/lib/db';
import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth';

async function getKepsekId(request: NextRequest): Promise<string | null> {
  const token = request.headers.get('Authorization')?.replace('Bearer ', '');
  if (!token) return null;
  const payload = await verifyToken(token);
  if (!payload || payload.role !== 'kepsek') return null;
  return payload.id as string;
}

export async function GET(request: NextRequest) {
  const kepsekId = await getKepsekId(request);
  if (!kepsekId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  // Global stats
  const totalGuru = await db.guru.count();
  const totalSantri = await db.santri.count();
  const totalHafalanKuat = await db.hafalan.count({ where: { status: 'KUAT' } });
  const totalHafalanBaru = await db.hafalan.count({ where: { status: 'BARU' } });
  const totalHafalanMurojaah = await db.hafalan.count({ where: { status: "MUROJA'AH" } });
  const totalJilidSelesai = await db.jilid.count({ where: { status: 'SELESAI' } });
  const totalJilidProses = await db.jilid.count({ where: { status: 'PROSES' } });
  const totalNgaji = await db.ngaji.count();

  // Per-guru stats
  const guruList = await db.guru.findMany({
    include: {
      _count: { select: { santri: true } },
      santri: {
        include: {
          _count: { select: { hafalan: true, ngaji: true, jilid: true } },
        },
      },
    },
    orderBy: { nama: 'asc' },
  });

  const guruStats = await Promise.all(
    guruList.map(async (g) => {
      const sIds = g.santri.map((s) => s.id);
      const jilidSelesai = await db.jilid.count({ where: { santriId: { in: sIds }, status: 'SELESAI' } });
      const hafalanKuat = await db.hafalan.count({ where: { santriId: { in: sIds }, status: 'KUAT' } });

      return {
        id: g.id,
        nama: g.nama,
        email: g.email,
        totalSantri: g._count.santri,
        jilidSelesai,
        hafalanKuat,
      };
    })
  );

  // Top santri (by jilid selesai)
  const allSantri = await db.santri.findMany({
    include: {
      guru: { select: { nama: true } },
    },
  });

  const topSantri = await Promise.all(
    allSantri.map(async (s) => {
      const jilidSelesai = await db.jilid.count({ where: { santriId: s.id, status: 'SELESAI' } });
      const hafalanKuat = await db.hafalan.count({ where: { santriId: s.id, status: 'KUAT' } });
      return {
        id: s.id,
        nama: s.nama,
        kelas: s.kelas,
        guruNama: s.guru.nama,
        jilidSelesai,
        hafalanKuat,
        score: jilidSelesai * 10 + hafalanKuat * 3,
      };
    })
  );

  topSantri.sort((a, b) => b.score - a.score);

  // Kelas distribution
  const kelasStats = await db.santri.groupBy({
    by: ['kelas'],
    _count: { id: true },
  });

  return NextResponse.json({
    totalGuru,
    totalSantri,
    totalHafalanKuat,
    totalHafalanBaru,
    totalHafalanMurojaah,
    totalJilidSelesai,
    totalJilidProses,
    totalNgaji,
    guruStats,
    topSantri: topSantri.slice(0, 10),
    kelasStats,
  });
}