import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { findById, updateRole, updateActive, deleteUser, listUsers } from "@/lib/localDb";
import { getAdapter } from "@/lib/db/driver";

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

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

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

    return NextResponse.json({ user });
  } catch (error) {
    console.error("[users/id] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch user" }, { status: 500 });
  }
}

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

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

    const body = await request.json();
    const { role, is_active } = body;

    // Validate fields — only role and is_active allowed
    const allowedKeys = ["role", "is_active"];
    for (const key of Object.keys(body)) {
      if (!allowedKeys.includes(key)) {
        return NextResponse.json({ error: `Field not allowed: ${key}` }, { status: 400 });
      }
    }

    // Role change
    if (role !== undefined) {
      if (!["admin", "user"].includes(role)) {
        return NextResponse.json({ error: "Role must be 'admin' or 'user'" }, { status: 400 });
      }

      // Prevent demoting last admin
      if (role !== "admin" && user.role === "admin") {
        const allUsers = await listUsers();
        const adminCount = allUsers.filter((u) => u.role === "admin").length;
        if (adminCount <= 1) {
          return NextResponse.json({ error: "Cannot demote the last admin" }, { status: 400 });
        }
      }

      await updateRole(id, role);
    }

    // Active toggle
    if (is_active !== undefined) {
      // Prevent disabling last admin
      if (!is_active && user.role === "admin") {
        const allUsers = await listUsers();
        const adminCount = allUsers.filter((u) => u.role === "admin" && u.is_active).length;
        if (adminCount <= 1) {
          return NextResponse.json({ error: "Cannot disable the last admin" }, { status: 400 });
        }
      }
      await updateActive(id, !!is_active);
    }

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

// DELETE /api/users/[id] - Delete user with cascade (admin-only)
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-delete
    if (id === adminPayload.userId) {
      return NextResponse.json({ error: "Cannot delete yourself" }, { status: 400 });
    }

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

    // Prevent deleting last admin
    if (user.role === "admin") {
      const allUsers = await listUsers();
      const adminCount = allUsers.filter((u) => u.role === "admin").length;
      if (adminCount <= 1) {
        return NextResponse.json({ error: "Cannot delete the last admin" }, { status: 400 });
      }
    }

    // Cascade delete: apiKeys, rateLimits, then user
    const db = await getAdapter();
    db.transaction(() => {
      db.run("DELETE FROM apiKeys WHERE userId = ?", [id]);
      db.run("DELETE FROM rateLimits WHERE userId = ?", [id]);
      db.run("DELETE FROM users WHERE id = ?", [id]);
    });

    return NextResponse.json({ message: "User deleted successfully" });
  } catch (error) {
    console.error("[users/id] DELETE error:", error);
    return NextResponse.json({ error: "Failed to delete user" }, { status: 500 });
  }
}
