import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireAdmin } from "@/lib/admin-auth";

/**
 * GET /api/admin/subscriptions — subscription monitoring data:
 *   - subscriptions: every family_subscriptions row joined to family + plan
 *   - webhookEvents: recent razorpay_webhook_events (debugging delivery)
 *   - summary: counts by status + MRR/ARR in paise (active+authenticated+pending)
 */
export async function GET(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const subscriptions = await sql`
    SELECT
      fs.id,
      fs.family_id,
      f.name                       AS family_name,
      p.name                       AS plan_name,
      p.price_paise,
      fs.status,
      fs.razorpay_subscription_id,
      fs.razorpay_customer_id,
      fs.current_start,
      fs.current_end,
      fs.cancelled_at,
      fs.ended_at,
      fs.created_at,
      fs.updated_at
    FROM family_subscriptions fs
    LEFT JOIN families f ON f.id = fs.family_id
    LEFT JOIN subscription_plans p ON p.id = fs.plan_id
    ORDER BY fs.created_at DESC
    LIMIT 200
  `;

  const webhookEvents = await sql`
    SELECT
      razorpay_event_id,
      event_type,
      received_at,
      payload->'payload'->'subscription'->'entity'->>'id'     AS sub_id,
      payload->'payload'->'subscription'->'entity'->>'status' AS sub_status
    FROM razorpay_webhook_events
    ORDER BY received_at DESC
    LIMIT 50
  `;

  // Summary: status counts + MRR (only entitled/recurring-active statuses).
  const byStatus: Record<string, number> = {};
  let mrrPaise = 0;
  for (const s of subscriptions as Record<string, unknown>[]) {
    const status = s.status as string;
    byStatus[status] = (byStatus[status] || 0) + 1;
    if (status === "active" || status === "authenticated" || status === "pending") {
      mrrPaise += Number(s.price_paise) || 0;
    }
  }

  return NextResponse.json({
    subscriptions,
    webhookEvents,
    summary: {
      total: subscriptions.length,
      byStatus,
      mrrPaise,
      arrPaise: mrrPaise * 12,
    },
  });
}

// POST /api/admin/subscriptions?action=reconcile — re-run entitlement sync.
// Delegates to the existing reconcile endpoint logic via internal import.
export { POST } from "../reconcile-subscriptions/route";
