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

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

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

interface UpdateBody {
  name: string;
  contact: string;
  email: 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, current_password, new_password } = body;

  if (!name?.trim() || !contact?.trim() || !email?.trim()) {
    return NextResponse.json({ error: "Name, contact, and email 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(),
  };

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

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