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

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 });
    }

    const guru = await db.guru.findUnique({ where: { email } });

    if (!guru) {
      return NextResponse.json({ error: 'Email tidak ditemukan' }, { status: 401 });
    }

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

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