import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { findById, updateApproval } from "@/lib/localDb";

export const dynamic = "force-dynamic";

async function requireAdmin() {
  const cookieStore = await cookies();
  const token = cookieStore.get("auth_token")?.value;
  if (!token) return null;
  const payload = await verifyToken(token);
  if (!payload || payload.role !== "admin") return null;
  return payload;
}

// POST /api/users/[id]/approve - Approve user
export async function POST(request, { params }) {
  try {
    const adminPayload = await requireAdmin();
    if (!adminPayload) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const { id } = await params;

    // Cannot self-approve
    if (id === adminPayload.userId) {
      return NextResponse.json({ error: "Cannot approve yourself" }, { status: 400 });
    }

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

    if (user.is_approved) {
      return NextResponse.json({ message: "User already approved", user });
    }

    await updateApproval(id, true);

    const updated = await findById(id);
    return NextResponse.json({ message: "User approved", user: updated });
  } catch (error) {
    console.error("[users/id/approve] POST error:", error);
    return NextResponse.json({ error: "Failed to approve user" }, { status: 500 });
  }
}

// DELETE /api/users/[id]/approve - Revoke approval
export async function DELETE(request, { params }) {
  try {
    const adminPayload = await requireAdmin();
    if (!adminPayload) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const { id } = await params;

    // Cannot self-revoke
    if (id === adminPayload.userId) {
      return NextResponse.json({ error: "Cannot revoke your own approval" }, { status: 400 });
    }

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

    // Prevent revoking last admin
    if (user.role === "admin") {
      const { listUsers } = await import("@/lib/localDb");
      const allUsers = await listUsers();
      const adminCount = allUsers.filter((u) => u.role === "admin").length;
      if (adminCount <= 1) {
        return NextResponse.json({ error: "Cannot revoke approval of the last admin" }, { status: 400 });
      }
    }

    await updateApproval(id, false);

    const updated = await findById(id);
    return NextResponse.json({ message: "Approval revoked", user: updated });
  } catch (error) {
    console.error("[users/id/approve] DELETE error:", error);
    return NextResponse.json({ error: "Failed to revoke approval" }, { status: 500 });
  }
}
