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/guru — List all guru with their santri count & stats
export async function GET(request: NextRequest) {
  const kepsekId = await getKepsekId(request);
  if (!kepsekId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

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

  // Get all santri IDs grouped by guru for batch queries
  const allSantriIds = guruList.flatMap((g) => g.santri.map((s) => s.id));

  const hafalanStats: any[] = await db.$queryRaw`
    SELECT santriId, status, COUNT(*) as cnt
    FROM "Hafalan"
    WHERE santriId IN (${allSantriIds.length > 0 ? allSantriIds.map(() => '?').join(',') : "'__none__'"})
    GROUP BY santriId, status
  `;

  const jilidStats: any[] = await db.$queryRaw`
    SELECT santriId, status, COUNT(*) as cnt
    FROM "Jilid"
    WHERE santriId IN (${allSantriIds.length > 0 ? allSantriIds.map(() => '?').join(',') : "'__none__'"})
    GROUP BY santriId, status
  `;

  const ngajiCounts: any[] = await db.$queryRaw`
    SELECT santriId, COUNT(*) as cnt
    FROM "Ngaji"
    WHERE santriId IN (${allSantriIds.length > 0 ? allSantriIds.map(() => '?').join(',') : "'__none__'"})
    GROUP BY santriId
  `;

  // Build lookup maps
  const hafalanMap = new Map<string, Record<string, number>>();
  hafalanStats.forEach((h: any) => {
    if (!hafalanMap.has(h.santriId)) hafalanMap.set(h.santriId, { KUAT: 0, "MUROJA'AH": 0, BARU: 0 });
    hafalanMap.get(h.santriId)![h.status] = h.cnt;
  });

  const jilidMap = new Map<string, Record<string, number>>();
  jilidStats.forEach((j: any) => {
    if (!jilidMap.has(j.santriId)) jilidMap.set(j.santriId, { SELESAI: 0, PROSES: 0, BELUM: 0 });
    jilidMap.get(j.santriId)![j.status] = j.cnt;
  });

  const ngajiMap = new Map<string, number>();
  ngajiCounts.forEach((n: any) => ngajiMap.set(n.santriId, n.cnt));

  const enriched = guruList.map((guru) => {
    const sIds = guru.santri.map((s) => s.id);
    let hafalanKuat = 0, hafalanMurojaah = 0, hafalanBaru = 0, totalJilidSelesai = 0, totalJilidProses = 0, totalNgaji = 0;

    sIds.forEach((sid) => {
      const hf = hafalanMap.get(sid);
      if (hf) { hafalanKuat += hf.KUAT || 0; hafalanMurojaah += hf["MUROJA'AH"] || 0; hafalanBaru += hf.BARU || 0; }
      const jl = jilidMap.get(sid);
      if (jl) { totalJilidSelesai += jl.SELESAI || 0; totalJilidProses += jl.PROSES || 0; }
      totalNgaji += ngajiMap.get(sid) || 0;
    });

    return {
      id: guru.id,
      nama: guru.nama,
      email: guru.email,
      createdAt: guru.createdAt,
      totalSantri: guru._count.santri,
      hafalanKuat,
      hafalanMurojaah,
      hafalanBaru,
      totalHafalan: hafalanKuat + hafalanMurojaah + hafalanBaru,
      totalJilidSelesai,
      totalJilidProses,
      totalNgaji,
    };
  });

  return NextResponse.json(enriched);
}

// POST /api/kepsek/guru — Create new guru account
export async function POST(request: NextRequest) {
  const kepsekId = await getKepsekId(request);
  if (!kepsekId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { nama, email, password } = await request.json();
  if (!nama || !email || !password) {
    return NextResponse.json({ error: 'Semua field wajib diisi' }, { status: 400 });
  }

  const existing = await db.guru.findUnique({ where: { email } });
  if (existing) {
    return NextResponse.json({ error: 'Email sudah terdaftar' }, { status: 409 });
  }

  const { hash } = await import('bcryptjs');
  const hashed = await hash(password, 10);

  const guru = await db.guru.create({
    data: { nama, email, password: hashed },
  });

  return NextResponse.json({ id: guru.id, nama: guru.nama, email: guru.email }, { status: 201 });
}

// PUT /api/kepsek/guru — Update guru
export async function PUT(request: NextRequest) {
  const kepsekId = await getKepsekId(request);
  if (!kepsekId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { id, nama, email, password } = await request.json();
  if (!id) return NextResponse.json({ error: 'ID wajib' }, { status: 400 });

  const data: Record<string, string> = {};
  if (nama) data.nama = nama;
  if (email) data.email = email;
  if (password) {
    const { hash } = await import('bcryptjs');
    data.password = await hash(password, 10);
  }

  const updated = await db.guru.update({ where: { id }, data });
  return NextResponse.json({ id: updated.id, nama: updated.nama, email: updated.email });
}

// DELETE /api/kepsek/guru — Delete guru and all their santri data
export async function DELETE(request: NextRequest) {
  const kepsekId = await getKepsekId(request);
  if (!kepsekId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { searchParams } = new URL(request.url);
  const id = searchParams.get('id');
  if (!id) return NextResponse.json({ error: 'ID wajib' }, { status: 400 });

  const santriIds = (await db.santri.findMany({ where: { guruId: id }, select: { id: true } })).map((s) => s.id);

  await db.hafalan.deleteMany({ where: { santriId: { in: santriIds } } });
  await db.ngaji.deleteMany({ where: { santriId: { in: santriIds } } });
  await db.jilid.deleteMany({ where: { santriId: { in: santriIds } } });
  await db.santri.deleteMany({ where: { guruId: id } });
  await db.guru.delete({ where: { id } });

  return NextResponse.json({ message: 'Guru dan semua data santri berhasil dihapus' });
}