import { db } from '@/lib/db';
import { compare } from 'bcryptjs';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    const { namaAnak, password } = await request.json();

    if (!namaAnak || !password) {
      return NextResponse.json({ error: 'Nama anak dan password wajib diisi' }, { status: 400 });
    }

    const santri = await db.santri.findFirst({
      where: { nama: namaAnak },
      include: { guru: { select: { nama: true } } },
    });

    if (!santri) {
      return NextResponse.json({ error: 'Nama anak tidak ditemukan' }, { status: 401 });
    }

    const valid = await compare(password, santri.passwordOrtu);
    if (!valid) {
      return NextResponse.json({ error: 'Password salah' }, { status: 401 });
    }

    return NextResponse.json({
      id: santri.id,
      nama: santri.nama,
      kelas: santri.kelas,
      kelompokBacaan: santri.kelompokBacaan,
      guruNama: santri.guru.nama,
      role: 'ortu',
    });
  } catch {
    return NextResponse.json({ error: 'Terjadi kesalahan server' }, { status: 500 });
  }
}