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 hafalan = await db.hafalan.findMany({
    where,
    include: { santri: { select: { nama: true, kelas: true } } },
    orderBy: { tanggal: 'desc' },
  });

  return NextResponse.json(hafalan);
}

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

  const { santriId, surah, ayatMulai, ayatAkhir, status, catatan } = await request.json();

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

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

  const hafalan = await db.hafalan.create({
    data: { santriId, surah, ayatMulai, ayatAkhir, status: status || 'BARU', catatan },
  });

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

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

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

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

  const data: Record<string, string> = {};
  if (status) data.status = status;
  if (catatan !== undefined) data.catatan = catatan;

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

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.hafalan.findFirst({
    where: { id, santri: { guruId } },
  });
  if (!existing) return NextResponse.json({ error: 'Data tidak ditemukan' }, { status: 404 });

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