import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";
import { getRazorpayConfig, razorpayAuthHeader, RAZORPAY_API_BASE } from "@/lib/billing/config";

/**
 * POST /api/subscriptions/cancel
 *
 * Initiates cancellation at Razorpay with cancel_at_cycle_end=1 — the family
 * keeps premium until the paid period ends. The actual state change happens
 * later via the subscription.cancelled webhook; this route only initiates.
 *
 * family_id from session (IDOR-safe). Cancels the family's own live sub only.
 */
export async function POST() {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;

  let cfg;
  try {
    cfg = getRazorpayConfig();
  } catch (e) {
    return NextResponse.json({ error: String(e) }, { status: 500 });
  }

  // Find the family's live subscription.
  const rows = await sql`
    SELECT razorpay_subscription_id, status FROM family_subscriptions
    WHERE family_id = ${familyId}
      AND status IN ('created','authenticated','active','pending')
    ORDER BY created_at DESC
    LIMIT 1
  `;
  const subId = rows[0]?.razorpay_subscription_id as string | undefined;
  if (!subId) {
    return NextResponse.json({ error: "No active subscription to cancel" }, { status: 404 });
  }

  try {
    const res = await fetch(`${RAZORPAY_API_BASE}/subscriptions/${subId}/cancel`, {
      method: "POST",
      headers: {
        Authorization: razorpayAuthHeader(cfg),
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ cancel_at_cycle_end: 1 }), // keep premium until period end
    });
    const data = await res.json();
    if (!res.ok) {
      console.error("Razorpay cancel failed:", data);
      return NextResponse.json(
        { error: data?.error?.description || "Failed to cancel subscription" },
        { status: 502 },
      );
    }
  } catch (e) {
    console.error("Razorpay cancel error:", e);
    return NextResponse.json({ error: "Failed to reach payment provider" }, { status: 502 });
  }

  return NextResponse.json({
    success: true,
    message: "Subscription will cancel at the end of your current billing period. You keep premium until then.",
  });
}
