/**
 * /api/billing — Billing & Subscription Management
 * ---------------------------------------------------
 * GET  — returns billing overview (subscription + usage + plans)
 * POST — actions: change_plan, cancel, check_limit, seed_plans
 *
 * Requires authentication. Uses the first org the user belongs to.
 */

import { NextResponse } from "next/server";
import { getCurrentUser, requirePermission } from "@/lib/auth";
import { log } from "@/lib/logger";
import {
  getBillingOverview,
  changePlan,
  cancelSubscription,
  checkLimit,
  seedDefaultPlans,
} from "@/lib/services/billing";
import type { LimitType } from "@/lib/services/billing";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  // Role check: billing requires admin or owner
  const denied = await requirePermission("billing");
  if (denied) return denied;

  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const membership = user.memberships?.[0];
  if (!membership) return NextResponse.json({ error: "No organization" }, { status: 400 });

  const { searchParams } = new URL(req.url);
  const orgId = searchParams.get("orgId") || membership.orgId;

  const start = Date.now();
  const overview = await getBillingOverview(orgId);
  log.apiRequest("/api/billing", "GET", 200, Date.now() - start, { userId: user.id });
  return NextResponse.json(overview);
}

export async function POST(req: Request) {
  const denied = await requirePermission("billing");
  if (denied) return denied;

  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const membership = user.memberships?.[0];
  if (!membership) return NextResponse.json({ error: "No organization" }, { status: 400 });

  const body = await req.json();
  const { action, orgId: bodyOrgId, planSlug, limitType } = body as {
    action: string;
    orgId?: string;
    planSlug?: string;
    limitType?: LimitType;
  };

  const orgId = bodyOrgId || membership.orgId;

  switch (action) {
    case "change_plan": {
      if (!planSlug) return NextResponse.json({ error: "planSlug required" }, { status: 400 });
      const sub = await changePlan(orgId, planSlug);
      if (!sub) return NextResponse.json({ error: "Plan not found" }, { status: 404 });
      return NextResponse.json({ subscription: sub });
    }

    case "cancel": {
      const sub = await cancelSubscription(orgId);
      if (!sub) return NextResponse.json({ error: "No subscription" }, { status: 404 });
      return NextResponse.json({ subscription: sub });
    }

    case "check_limit": {
      if (!limitType) return NextResponse.json({ error: "limitType required" }, { status: 400 });
      const result = await checkLimit(orgId, limitType);
      return NextResponse.json(result);
    }

    case "seed_plans": {
      await seedDefaultPlans();
      return NextResponse.json({ ok: true, message: "Default plans seeded" });
    }

    default:
      return NextResponse.json({ error: "Unknown action" }, { status: 400 });
  }
}
