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

export async function GET(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 !== "SISWA") {
      return NextResponse.json({ success: false, message: "Forbidden" }, { status: 403 });
    }

    const siswa = await prisma.siswa.findFirst({
      where: { userId: payload.userId },
      include: { jurusan: true, rombel: true },
    });

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

    return NextResponse.json({ success: true, data: siswa });
  } catch (error) {
    console.error("Error fetching siswa profile:", error);
    return NextResponse.json({ success: false, message: "Internal Server Error" }, { status: 500 });
  }
}

const UpdateProfileSchema = z.object({
  nama: z.string().min(1, "Nama tidak boleh kosong"),
  agama: z.string().min(1, "Agama tidak boleh kosong"),
  noWa: z.string().optional(),
  noWaOrtu: z.string().optional(),

  // New Fields
  tempatLahir: z.string().optional(),
  tanggalLahir: z.coerce.date().optional(),
  alamat: z.string().optional(),
  desa: z.string().optional(),
  kecamatan: z.string().optional(),
  kabupaten: z.string().optional(),
  namaAyah: z.string().optional(),
  pekerjaanAyah: z.string().optional(),
  namaIbu: z.string().optional(),
  pekerjaanIbu: z.string().optional(),
});

export async function PUT(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 !== "SISWA") {
      return NextResponse.json({ success: false, message: "Forbidden" }, { status: 403 });
    }

    const body = await request.json();
    const validatedData = UpdateProfileSchema.parse(body);

    const siswa = await prisma.siswa.findFirst({
      where: { userId: payload.userId },
    });

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

    const updatedSiswa = await prisma.siswa.update({
      where: { id: siswa.id },
      data: validatedData,
    });

    // Also update User name if needed? Sysnc.
    await prisma.user.update({
      where: { id: payload.userId },
      data: { name: validatedData.nama },
    });

    return NextResponse.json({ success: true, data: updatedSiswa, message: "Profil berhasil diperbarui" });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ success: false, message: error.errors[0].message }, { status: 400 });
    }
    console.error("Error updating profile:", error);
    return NextResponse.json({ success: false, message: "Internal Server Error" }, { status: 500 });
  }
}
