import { NextRequest, NextResponse } from "next/server";
import { getTokenFromRequest, verifyToken } from "@/lib/jwt";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";

export async function POST(request: NextRequest) {
  try {
    const token = getTokenFromRequest(request);
    if (!token) return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 });

    const payload = verifyToken(token);
    if (!payload || payload.role !== "ADMIN") {
      return NextResponse.json({ success: false, message: "Forbidden" }, { status: 403 });
    }

    const body = await request.json();
    const { siswaId } = body;

    if (!siswaId) {
      return NextResponse.json({ success: false, message: "Siswa ID required" }, { status: 400 });
    }

    // Fetch Siswa
    const siswa = await prisma.siswa.findUnique({
      where: { id: siswaId },
      include: { user: true, rombel: true },
    });

    if (!siswa) {
      return NextResponse.json({ success: false, message: "Siswa not found" }, { status: 404 });
    }

    if (siswa.user) {
      return NextResponse.json({ success: false, message: "Siswa already has a user account" }, { status: 400 });
    }

    const username = siswa.nis;
    const passwordRaw = siswa.nisn || siswa.nis; // Default password is NISN
    const hashedPassword = await bcrypt.hash(passwordRaw, 10);

    // Create User and Link
    const newUser = await prisma.user.create({
      data: {
        username: username,
        password: hashedPassword,
        name: siswa.nama,
        role: "SISWA",
        status: "AKTIF",
        nisn: siswa.nisn,
        kelas: siswa.rombel?.namaRombel, // Use rombel name
        siswa: {
          connect: { id: siswa.id },
        },
      },
    });

    return NextResponse.json({
      success: true,
      message: `User created. Username: ${username}, Password: ${passwordRaw}`,
      data: newUser,
    });
  } catch (error) {
    console.error("Error generating user:", error);
    return NextResponse.json({ success: false, message: "Internal Server Error" }, { status: 500 });
  }
}
