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

async function getGuruId(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 !== 'guru') return null;
  return payload.id as string;
}

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

  const { searchParams } = new URL(request.url);
  const santriId = searchParams.get('santriId');

  const where: Record<string, unknown> = { santri: { guruId } };
  if (santriId) where.santriId = santriId;

  const jilid = await db.jilid.findMany({
    where,
    include: { santri: { select: { nama: true, kelas: true } } },
    orderBy: { createdAt: 'asc' },
  });

  return NextResponse.json(jilid);
}

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

  const { santriId, namaJilid, halaman, status, tanggalSelesai, catatanGuru } = await request.json();

  if (!santriId || !namaJilid) {
    return NextResponse.json({ error: 'Field wajib: santriId, namaJilid' }, { status: 400 });
  }

  const santri = await db.santri.findFirst({ where: { id: santriId, guruId } });
  if (!santri) return NextResponse.json({ error: 'Santri tidak ditemukan' }, { status: 404 });

  // Check if jilid already exists for this santri
  const existing = await db.jilid.findFirst({ where: { santriId, namaJilid } });
  if (existing) {
    const updated = await db.jilid.update({
      where: { id: existing.id },
      data: {
        status: status || existing.status,
        halaman: halaman !== undefined && halaman !== null && halaman !== '' ? parseInt(halaman) : existing.halaman,
        tanggalSelesai: tanggalSelesai ? new Date(tanggalSelesai) : existing.tanggalSelesai,
        catatanGuru: catatanGuru !== undefined ? catatanGuru : existing.catatanGuru,
      },
    });
    return NextResponse.json(updated);
  }

  const newJilid = await db.jilid.create({
    data: {
      santriId,
      namaJilid,
      halaman: halaman ? parseInt(halaman) : null,
      status: status || 'BELUM',
      tanggalSelesai: tanggalSelesai ? new Date(tanggalSelesai) : null,
      catatanGuru,
    },
  });

  return NextResponse.json(newJilid, { status: 201 });
}

export async function DELETE(request: NextRequest) {
  const guruId = await getGuruId(request);
  if (!guruId) 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 existing = await db.jilid.findFirst({
    where: { id, santri: { guruId } },
  });
  if (!existing) return NextResponse.json({ error: 'Data tidak ditemukan' }, { status: 404 });

  await db.jilid.delete({ where: { id } });
  return NextResponse.json({ message: 'Data jilid berhasil dihapus' });
}