import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";

export async function PATCH(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (staffUser.role !== "ADMIN" && staffUser.role !== "SUPER_ADMIN") {
      return NextResponse.json(
        { error: "Only administrators can modify account status" },
        { status: 403 },
      );
    }

    const body = await request.json();
    const { action, reason } = body;

    if (!action || !["suspend", "activate"].includes(action)) {
      return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }

    if (!reason || reason.trim().length < 5) {
      return NextResponse.json(
        { error: "Reason required (minimum 5 characters)" },
        { status: 400 },
      );
    }

    const user = await prisma.users.findUnique({
      where: { id: params.id },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        isActive: true,
        isSuspended: true,
      },
    });

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

    if (
      (user.role === "ADMIN" || user.role === "SUPER_ADMIN") &&
      action === "suspend"
    ) {
      return NextResponse.json(
        { error: "Cannot suspend administrator accounts" },
        { status: 403 },
      );
    }

    const isSuspending = action === "suspend";

    const updated = await prisma.users.update({
      where: { id: params.id },
      data: {
        isSuspended: isSuspending,
        isActive: !isSuspending,
        suspendedAt: isSuspending ? new Date() : null,
        suspendedBy: isSuspending ? staffUser.id : null,
        suspendedReason: isSuspending ? reason.trim() : null,
        updatedAt: new Date(),
      },
    });

    // Write audit log
    try {
      await prisma.audit_logs.create({
        data: {
          userId: params.id,
          type: isSuspending ? "account_suspended" : "account_activated",
          action: `Account ${isSuspending ? "suspended" : "activated"} by ${staffUser.email}`,
          success: true,
          ipAddress: request.headers.get("x-forwarded-for") || "unknown",
          metadata: JSON.stringify({ reason: reason.trim(), staffId: staffUser.id }),
        },
      });
    } catch (auditErr) {
      console.error("Audit log write failed (non-critical):", auditErr);
    }

    console.log(
      `${isSuspending ? "Suspended" : "Activated"} user ${user.email}`,
    );

    const { password, ...userWithoutPassword } = updated;

    return NextResponse.json({
      success: true,
      message: `Account ${isSuspending ? "suspended" : "activated"} successfully`,
      user: userWithoutPassword,
    });
  } catch (error) {
    console.error("Failed to update user status:", error);
    return NextResponse.json(
      { error: "Failed to update account status" },
      { status: 500 },
    );
  }
}
