import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { findById } from "@/lib/localDb";
import { getByUserId, updateLimits, createDefaults } from "@/lib/db/repos/rateLimitRepo";

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

const VALID_LIMIT_KEYS = ["rtpMinute", "rtpDay", "tokenLimitMonthly", "creditLimit", "maxConcurrent"];

function validateLimits(body) {
  const errors = [];
  for (const key of Object.keys(body)) {
    if (!VALID_LIMIT_KEYS.includes(key)) {
      errors.push(`Unknown field: ${key}`);
      continue;
    }
    const value = body[key];
    // creditLimit can be 0, all others must be >= 1
    if (typeof value !== "number" || isNaN(value)) {
      errors.push(`${key} must be a number`);
    } else if (key === "creditLimit" ? value < 0 : value < 1) {
      errors.push(`${key} must be ${key === "creditLimit" ? ">= 0" : ">= 1"}`);
    }
  }
  return errors;
}

// GET /api/users/[id]/limits - Get rate limits for a user
export async function GET(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 limits = await getByUserId(id);
    if (!limits) {
      return NextResponse.json({ limits: null, message: "No rate limits configured" }, { status: 200 });
    }

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

// POST /api/users/[id]/limits - Initialize default rate limits for user without any
export async function POST(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 });
    }

    // Check if already has limits
    const existing = await getByUserId(id);
    if (existing) {
      return NextResponse.json({ error: "User already has rate limits configured" }, { status: 409 });
    }

    const body = await request.json().catch(() => ({}));
    const { packageId } = body || {};

    // Create defaults (from package if provided)
    await createDefaults(id, packageId || null);

    const limits = await getByUserId(id);
    return NextResponse.json({ limits, message: "Rate limits initialized" }, { status: 201 });
  } catch (error) {
    console.error("[users/id/limits] POST error:", error);
    return NextResponse.json({ error: "Failed to initialize rate limits" }, { status: 500 });
  }
}

// PATCH /api/users/[id]/limits - Update rate limits (partial)
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();
    if (!body || Object.keys(body).length === 0) {
      return NextResponse.json({ error: "Request body is required" }, { status: 400 });
    }

    const errors = validateLimits(body);
    if (errors.length > 0) {
      return NextResponse.json({ error: "Validation failed", details: errors }, { status: 400 });
    }

    await updateLimits(id, body);

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