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 search = searchParams.get('search') || '';
  const kelas = searchParams.get('kelas') || '';
  const kelompok = searchParams.get('kelompok') || '';

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

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

  return NextResponse.json(santri);
}

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

  const { nama, kelas, kelompokBacaan, passwordOrtu } = await request.json();

  if (!nama || !kelas || !kelompokBacaan || !passwordOrtu) {
    return NextResponse.json({ error: 'Semua field wajib diisi' }, { status: 400 });
  }

  const { hash } = await import('bcryptjs');
  const hashedPassword = await hash(passwordOrtu, 10);

  const santri = await db.santri.create({
    data: { nama, kelas, kelompokBacaan, passwordOrtu: hashedPassword, guruId },
  });

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

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

  const { id, nama, kelas, kelompokBacaan, passwordOrtu } = await request.json();

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

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

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

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

  return NextResponse.json({ message: 'Santri berhasil dihapus' });
}