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

export async function GET(request: NextRequest) {
  const token = request.headers.get('Authorization')?.replace('Bearer ', '');
  if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const payload = await verifyToken(token);
  if (!payload) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  if (payload.role === 'guru') {
    const guruId = payload.id as string;

    const totalSantri = await db.santri.count({ where: { guruId } });
    const totalHafalan = await db.hafalan.count({
      where: { santri: { guruId }, status: 'KUAT' },
    });
    const totalJilidSelesai = await db.jilid.count({
      where: { santri: { guruId }, status: 'SELESAI' },
    });
    const totalJilidProses = await db.jilid.count({
      where: { santri: { guruId }, status: 'PROSES' },
    });
    const hafalanBaru = await db.hafalan.count({
      where: { santri: { guruId }, status: 'BARU' },
    });
    const hafalanMurojaah = await db.hafalan.count({
      where: { santri: { guruId }, status: "MUROJA'AH" },
    });
    const totalNgaji = await db.ngaji.count({
      where: { santri: { guruId } },
    });

    // Per-kelas stats
    const kelasStats = await db.santri.groupBy({
      by: ['kelas'],
      where: { guruId },
      _count: { id: true },
    });

    // Kelompok bacaan distribution
    const kelompokStats = await db.santri.groupBy({
      by: ['kelompokBacaan'],
      where: { guruId },
      _count: { id: true },
    });

    // Recent activities
    const recentHafalan = await db.hafalan.findMany({
      where: { santri: { guruId } },
      include: { santri: { select: { nama: true, kelas: true } } },
      orderBy: { createdAt: 'desc' },
      take: 5,
    });

    const recentNgaji = await db.ngaji.findMany({
      where: { santri: { guruId } },
      include: { santri: { select: { nama: true, kelas: true } } },
      orderBy: { createdAt: 'desc' },
      take: 5,
    });

    return NextResponse.json({
      totalSantri,
      totalHafalan,
      totalJilidSelesai,
      totalJilidProses,
      hafalanBaru,
      hafalanMurojaah,
      totalNgaji,
      kelasStats,
      kelompokStats,
      recentHafalan,
      recentNgaji,
    });
  }

  // Orang Tua view
  if (payload.role === 'ortu') {
    const santriId = payload.id as string;

    const totalHafalan = await db.hafalan.count({ where: { santriId } });
    const hafalanKuat = await db.hafalan.count({ where: { santriId, status: 'KUAT' } });
    const hafalanBaru = await db.hafalan.count({ where: { santriId, status: 'BARU' } });
    const hafalanMurojaah = await db.hafalan.count({ where: { santriId, status: "MUROJA'AH" } });
    const totalNgaji = await db.ngaji.count({ where: { santriId } });

    const jilid = await db.jilid.findMany({
      where: { santriId },
      orderBy: { createdAt: 'asc' },
    });

    const jilidSelesai = jilid.filter(j => j.status === 'SELESAI').length;
    const jilidProses = jilid.filter(j => j.status === 'PROSES').length;

    const hafalanList = await db.hafalan.findMany({
      where: { santriId },
      orderBy: { tanggal: 'desc' },
    });

    const ngajiList = await db.ngaji.findMany({
      where: { santriId },
      orderBy: { tanggal: 'desc' },
    });

    return NextResponse.json({
      totalHafalan,
      hafalanKuat,
      hafalanBaru,
      hafalanMurojaah,
      totalNgaji,
      jilidSelesai,
      jilidProses,
      jilid,
      hafalanList,
      ngajiList,
    });
  }

  return NextResponse.json({ error: 'Role tidak valid' }, { status: 403 });
}