import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { findById } from "@/lib/localDb";
import {
  getUserPackage,
  assignPackage,
  updateUserPackageOverrides,
  getActivePackages,
} from "@/lib/db/repos/packagesRepo";

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]/package - Get user's current package assignment
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 });
    }

    const userPackage = await getUserPackage(id);
    const packages = await getActivePackages();

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

// PUT /api/users/[id]/package - Assign or update package for user
export async function PUT(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 });
    }

    const body = await request.json();

    const { packageId, overrides } = body;

    if (!packageId) {
      return NextResponse.json({ error: "packageId is required" }, { status: 400 });
    }

    // Validate override values if provided
    const overrideFields = [
      "rtpMinuteOverride",
      "rtpDayOverride",
      "tokenLimitMonthlyOverride",
      "creditLimitOverride",
      "maxConcurrentOverride",
    ];
    const cleanOverrides = {};
    if (overrides) {
      for (const field of overrideFields) {
        if (overrides[field] !== undefined && overrides[field] !== null && overrides[field] !== "") {
          const num = Number(overrides[field]);
          if (isNaN(num) || num < 0) {
            return NextResponse.json(
              { error: `${field} must be a non-negative number` },
              { status: 400 }
            );
          }
          cleanOverrides[field] = num;
        }
      }
    }

    const existing = await getUserPackage(id);

    let result;
    if (existing && existing.packageId === packageId) {
      // Same package - just update overrides
      result = await updateUserPackageOverrides(id, cleanOverrides);
    } else {
      // New package assignment
      result = await assignPackage(id, packageId, cleanOverrides);
    }

    // Re-fetch with package details
    const userPackage = await getUserPackage(id);
    return NextResponse.json({ userPackage });
  } catch (error) {
    console.error("[users/id/package] PUT error:", error);
    return NextResponse.json({ error: "Failed to update package" }, { status: 500 });
  }
}
