import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import {
  getPackageById,
  updatePackage,
  deletePackage,
  getAllPackages,
} from "@/lib/db/repos/packagesRepo";
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/packages/[id] - Get single package (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 pkg = await getPackageById(id);
    if (!pkg) {
      return NextResponse.json({ error: "Package not found" }, { status: 404 });
    }

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

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

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

    const body = await request.json();

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

    // Check name uniqueness if name is being changed
    if (body.name !== undefined) {
      if (typeof body.name !== "string" || body.name.trim() === "") {
        return NextResponse.json({ error: "Name cannot be empty" }, { status: 400 });
      }
      const allPackages = await getAllPackages();
      const duplicate = allPackages.find(
        (p) => p.id !== id && p.name.toLowerCase() === body.name.trim().toLowerCase()
      );
      if (duplicate) {
        return NextResponse.json(
          { error: "A package with this name already exists" },
          { status: 409 }
        );
      }
    }

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

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

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

    // Check if package is assigned to any users
    const db = await getAdapter();
    const row = db.get(
      `SELECT COUNT(*) as count FROM userPackages WHERE packageId = ?`,
      [id]
    );
    const assignedCount = row?.count ?? 0;

    if (assignedCount > 0) {
      // Check for force flag in query string
      const url = new URL(request.url);
      const force = url.searchParams.get("force") === "true";

      if (!force) {
        return NextResponse.json(
          {
            error: `Package is assigned to ${assignedCount} user(s). Pass ?force=true to confirm deletion.`,
            assignedCount,
          },
          { status: 409 }
        );
      }

      // Force delete: remove user-package assignments first
      db.run(`DELETE FROM userPackages WHERE packageId = ?`, [id]);
    }

    await deletePackage(id);
    return NextResponse.json({ message: "Package deleted successfully" });
  } catch (error) {
    console.error("[packages/id] DELETE error:", error);
    return NextResponse.json({ error: "Failed to delete package" }, { status: 500 });
  }
}
