import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { getAllPackages, createPackage } 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/packages - List all packages (admin-only)
export async function GET() {
  try {
    const admin = await requireAdmin();
    if (!admin) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const packages = await getAllPackages();
    return NextResponse.json({ packages });
  } catch (error) {
    console.error("[packages] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch packages" }, { status: 500 });
  }
}

// POST /api/packages - Create package (admin-only)
export async function POST(request) {
  try {
    const admin = await requireAdmin();
    if (!admin) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const body = await request.json();

    // Validate required fields
    if (!body.name || typeof body.name !== "string" || body.name.trim() === "") {
      return NextResponse.json({ error: "Name is required" }, { status: 400 });
    }

    // Validate numeric fields must be positive if provided
    const numericFields = [
      "rtpMinute",
      "rtpDay",
      "tokenLimitMonthly",
      "creditLimit",
      "creditToTokenRatio",
      "maxConcurrent",
      "durationDays",
      "price",
    ];
    for (const field of numericFields) {
      if (body[field] !== undefined && (typeof body[field] !== "number" || body[field] < 0)) {
        return NextResponse.json(
          { error: `${field} must be a positive number` },
          { status: 400 }
        );
      }
    }

    const pkg = await createPackage(body);
    return NextResponse.json({ package: pkg }, { status: 201 });
  } catch (error) {
    console.error("[packages] POST error:", error);
    return NextResponse.json({ error: "Failed to create package" }, { status: 500 });
  }
}
