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;
}

// GET /api/kepsek/santri — List all santri across all guru with details
export async function GET(request: NextRequest) {
  const kepsekId = await getKepsekId(request);
  if (!kepsekId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { searchParams } = new URL(request.url);
  const search = searchParams.get('search') || '';
  const kelas = searchParams.get('kelas') || '';
  const guruId = searchParams.get('guruId') || '';

  const where: Record<string, unknown> = {};
  if (search) where.nama = { contains: search };
  if (kelas) where.kelas = kelas;
  if (guruId) where.guruId = guruId;

  const santriList = await db.santri.findMany({
    where,
    include: {
      guru: { select: { id: true, nama: true } },
      _count: { select: { hafalan: true, ngaji: true, jilid: true } },
    },
    orderBy: [{ guruId: 'asc' }, { nama: 'asc' }],
  });

  // Enrich each santri with stats
  const enriched = await Promise.all(
    santriList.map(async (s) => {
      const hafalanKuat = await db.hafalan.count({ where: { santriId: s.id, status: 'KUAT' } });
      const totalJilidSelesai = await db.jilid.count({ where: { santriId: s.id, status: 'SELESAI' } });

      return {
        id: s.id,
        nama: s.nama,
        kelas: s.kelas,
        kelompokBacaan: s.kelompokBacaan,
        guruId: s.guruId,
        guruNama: s.guru.nama,
        totalHafalan: s._count.hafalan,
        hafalanKuat,
        totalNgaji: s._count.ngaji,
        totalJilidSelesai,
        totalJilid: s._count.jilid,
        createdAt: s.createdAt,
      };
    })
  );

  return NextResponse.json(enriched);
}