import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { getStudent } from "@/lib/studentAuth";

export async function GET() {
  const auth: any = await getStudent();
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const student = await prisma.students.findUnique({
    where: { id: auth.id },
    select: {
      id: true,
      student_id: true,
      name: true,
      contact: true,
      email: true,
      mother_first_name: true,
      mother_last_name: true,
      father_first_name: true,
      father_last_name: true,
      address: true,
    },
  });

  if (!student) return NextResponse.json({ error: "Student not found" }, { status: 404 });

  return NextResponse.json({ data: student });
}

interface UpdateBody {
  name: string;
  contact: string;
  email: string;
  mother_first_name: string;
  mother_last_name: string;
  father_first_name: string;
  father_last_name: string;
  address: string;
  current_password?: string;
  new_password?: string;
}

export async function PUT(req: NextRequest) {
  const auth: any = await getStudent();
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body: UpdateBody = await req.json();
  const {
    name,
    contact,
    email,
    mother_first_name,
    mother_last_name,
    father_first_name,
    father_last_name,
    address,
    current_password,
    new_password,
  } = body;

  if (
    !name?.trim() ||
    !contact?.trim() ||
    !email?.trim() ||
    !mother_first_name?.trim() ||
    !mother_last_name?.trim() ||
    !father_first_name?.trim() ||
    !father_last_name?.trim() ||
    !address?.trim()
  ) {
    return NextResponse.json(
      { error: "Name, contact, email, parent names, and address are required" },
      { status: 400 }
    );
  }

  const student = await prisma.students.findUnique({ where: { id: auth.id } });
  if (!student) return NextResponse.json({ error: "Student not found" }, { status: 404 });

  // Email uniqueness check (excluding self)
  const emailTaken = await prisma.students.findFirst({
    where: { email: email.trim(), id: { not: auth.id } },
  });
  if (emailTaken) {
    return NextResponse.json({ error: "That email is already in use" }, { status: 409 });
  }

  const data: Record<string, any> = {
    name: name.trim(),
    contact: contact.replace(/\D/g, ""),
    email: email.trim(),
    mother_first_name: mother_first_name.trim(),
    mother_last_name: mother_last_name.trim(),
    father_first_name: father_first_name.trim(),
    father_last_name: father_last_name.trim(),
    address: address.trim(),
  };

  // Password change is optional, but if new_password is provided, current_password
  // must be provided and must match — self-service accounts shouldn't be able to
  // silently rotate the password without proving they know the current one.
  if (new_password) {
    if (!current_password) {
      return NextResponse.json({ error: "Current password is required to set a new password" }, { status: 400 });
    }

    const matches = await bcrypt.compare(current_password, student.password);
    if (!matches) {
      return NextResponse.json({ error: "Current password is incorrect" }, { status: 401 });
    }

    data.password = await bcrypt.hash(new_password, 10);
  }

  const updated = await prisma.students.update({
    where: { id: auth.id },
    data,
    select: {
      id: true,
      student_id: true,
      name: true,
      contact: true,
      email: true,
      mother_first_name: true,
      mother_last_name: true,
      father_first_name: true,
      father_last_name: true,
      address: true,
    },
  });

  return NextResponse.json({ data: updated, message: "Profile updated successfully" });
}