import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import {
  SESSION_COOKIE,
  SESSION_MAX_AGE_SECONDS,
  requireRole,
  signSession,
} from "@/lib/auth";

/** The central administrator's own credential profile. */
export async function GET() {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const user = await prisma.user.findUnique({
    where: { id: session.userId },
    select: {
      id: true,
      name: true,
      email: true,
      role: true,
      lastLoginAt: true,
      createdAt: true,
    },
  });
  if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json({ profile: user });
}

/** Update the central credential profile (name / email). The session cookie
 *  is re-signed so the embedded name/email stay in sync everywhere. */
export async function PUT(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    const email = String(body.email ?? "").trim().toLowerCase();
    if (!name || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
      return NextResponse.json({ error: "Invalid name or email" }, { status: 400 });
    }

    if (email !== session.email) {
      const clash = await prisma.user.findUnique({
        where: { email },
        select: { id: true },
      });
      if (clash && clash.id !== session.userId) {
        return NextResponse.json({ error: "EMAIL_EXISTS" }, { status: 409 });
      }
    }

    const user = await prisma.user.update({
      where: { id: session.userId },
      data: { name, email },
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        username: true,
        institutionId: true,
        lastLoginAt: true,
        createdAt: true,
      },
    });

    // keep the signed session (name/email are embedded in the JWT) in sync
    const token = await signSession({
      userId: user.id,
      role: user.role,
      name: user.name,
      email: user.email,
      username: user.username,
      institutionId: user.institutionId,
    });
    const res = NextResponse.json({
      profile: {
        id: user.id,
        name: user.name,
        email: user.email,
        role: user.role,
        lastLoginAt: user.lastLoginAt,
        createdAt: user.createdAt,
      },
    });
    // Only mark the cookie Secure on real HTTPS — mirrors the login route
    const proto =
      req.headers.get("x-forwarded-proto")?.split(",")[0].trim() ??
      new URL(req.url).protocol.replace(":", "");
    res.cookies.set(SESSION_COOKIE, token, {
      httpOnly: true,
      sameSite: "lax",
      secure: proto === "https",
      maxAge: SESSION_MAX_AGE_SECONDS,
      path: "/",
    });
    return res;
  } catch {
    return NextResponse.json({ error: "Update failed" }, { status: 500 });
  }
}

/** Change the central credential's password (current password required). */
export async function POST(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const body = await req.json();
    const currentPassword = String(body.currentPassword ?? "");
    const newPassword = String(body.newPassword ?? "");
    if (newPassword.length < 6) {
      return NextResponse.json({ error: "Password must be at least 6 characters" }, { status: 400 });
    }

    const user = await prisma.user.findUnique({
      where: { id: session.userId },
      select: { passwordHash: true },
    });
    if (!user || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
      return NextResponse.json({ error: "WRONG_PASSWORD" }, { status: 403 });
    }

    const passwordHash = await bcrypt.hash(newPassword, 10);
    await prisma.user.update({
      where: { id: session.userId },
      data: { passwordHash },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Password change failed" }, { status: 500 });
  }
}
