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

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

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

    // Use raw query to avoid Prisma client cache issues with new models
    const results: any[] = await db.$queryRaw`
      SELECT * FROM "Kepsek" WHERE email = ${email} LIMIT 1
    `;

    if (!results || results.length === 0) {
      return NextResponse.json({ error: 'Email tidak ditemukan' }, { status: 401 });
    }

    const kepsek = results[0];

    const { compare } = await import('bcryptjs');
    const valid = await compare(password, kepsek.password);

    if (!valid) {
      return NextResponse.json({ error: 'Password salah' }, { status: 401 });
    }

    return NextResponse.json({
      id: kepsek.id,
      nama: kepsek.nama,
      email: kepsek.email,
      role: 'kepsek',
    });
  } catch {
    return NextResponse.json({ error: 'Terjadi kesalahan server' }, { status: 500 });
  }
}