import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const [allShops, dbPlans, dbSubs, dbEvents] = await Promise.all([
      db.getAllShops(),
      db.getPlans(),
      db.getSubscriptions().catch(() => []),
      db.getRecentBillingEvents(100).catch(() => []),
    ]);

    // Build real store subscription list
    const allSubs = allShops.map((shop) => {
      const planObj = dbPlans.find((p) => p.id.toLowerCase() === (shop.plan || 'basic').toLowerCase());
      const planPrice = planObj ? planObj.price : shop.plan === 'accelerate' ? 99 : shop.plan === 'growth' ? 13 : 0;
      const subStatus = shop.subscription_status || (planPrice > 0 ? 'active' : 'free');
      const isPaid = (shop.status === 'installed' && subStatus === 'active' && planPrice > 0);

      return {
        id: `sub_${shop.id}`,
        shop_id: shop.id,
        shopify_domain: shop.shopify_domain,
        shop_name: shop.shop_name || shop.shopify_domain.replace('.myshopify.com', ''),
        plan_id: shop.plan || 'growth',
        plan_name: planObj ? planObj.name : `${(shop.plan || 'growth').toUpperCase()} Plan`,
        price: planPrice,
        currency: shop.currency || 'USD',
        billing_cycle: shop.billing_cycle || 'monthly',
        status: subStatus,
        is_paid: isPaid,
        trial_days: shop.trial_days || 0,
        trial_starts_at: shop.trial_starts_at,
        trial_ends_at: shop.trial_ends_at,
        created_at: shop.installed_at || shop.created_at,
        is_demo: false,
      };
    });

    // Compute metrics with strict business logic
    const activePaid = allSubs.filter((s) => s.status === 'active' && s.price > 0);
    const freeTrials = allSubs.filter((s) => s.status === 'trial');
    const freePlan = allSubs.filter((s) => s.status === 'free' || s.price === 0);
    const cancelled = allSubs.filter((s) => s.status === 'cancelled');
    const pastDue = allSubs.filter((s) => (s.status as string) === 'past_due');

    const totalMRR = activePaid.reduce((sum, s) => sum + s.price, 0);
    const totalARR = totalMRR * 12;

    const monthlyCount = activePaid.filter((s) => s.billing_cycle === 'monthly').length;
    const yearlyCount = activePaid.filter((s) => s.billing_cycle === 'yearly').length;

    // Real database billing events
    const realBillingEvents = dbEvents.map((e: any) => ({
      id: e.id,
      shop_id: e.shop_id,
      shopify_domain: e.shopify_domain,
      shop_name: e.shopify_domain.replace('.myshopify.com', ''),
      event_type: e.event_type,
      amount: parseFloat(e.amount) || 0,
      currency: e.currency || 'USD',
      status: e.status || 'verified',
      plan_name: 'Growth Plan',
      shopify_charge_id: e.shopify_charge_id,
      billing_date: e.billing_date || e.created_at,
      is_demo: false,
    }));

    // If there's an active paid store with no event row yet, show verified active charge
    if (realBillingEvents.length === 0 && activePaid.length > 0) {
      for (const p of activePaid) {
        realBillingEvents.push({
          id: `bill_${p.shop_id}_active`,
          shop_id: p.shop_id,
          shopify_domain: p.shopify_domain,
          shop_name: p.shop_name,
          event_type: 'subscription_payment',
          amount: p.price,
          currency: p.currency,
          status: 'verified',
          plan_name: p.plan_name,
          shopify_charge_id: `sub_${p.shop_id}`,
          billing_date: p.created_at || new Date().toISOString(),
          is_demo: false,
        });
      }
    }

    // Revenue by plan breakdown
    const revenueByPlan = {
      basic: {
        count: freePlan.length,
        revenue: 0,
        percentage: allSubs.length > 0 ? Math.round((freePlan.length / allSubs.length) * 100) : 0,
      },
      growth: {
        count: activePaid.filter((s) => s.plan_id === 'growth').length,
        revenue: activePaid.filter((s) => s.plan_id === 'growth').reduce((sum, s) => sum + s.price, 0),
        percentage: allSubs.length > 0 ? Math.round((activePaid.filter((s) => s.plan_id === 'growth').length / allSubs.length) * 100) : 0,
      },
      accelerate: {
        count: activePaid.filter((s) => s.plan_id === 'accelerate').length,
        revenue: activePaid.filter((s) => s.plan_id === 'accelerate').reduce((sum, s) => sum + s.price, 0),
        percentage: allSubs.length > 0 ? Math.round((activePaid.filter((s) => s.plan_id === 'accelerate').length / allSubs.length) * 100) : 0,
      },
      enterprise: {
        count: activePaid.filter((s) => s.plan_id === 'enterprise').length,
        revenue: activePaid.filter((s) => s.plan_id === 'enterprise').reduce((sum, s) => sum + s.price, 0),
        percentage: allSubs.length > 0 ? Math.round((activePaid.filter((s) => s.plan_id === 'enterprise').length / allSubs.length) * 100) : 0,
      },
    };

    return NextResponse.json({
      success: true,
      metrics: {
        activePaidCount: activePaid.length,
        activePaidSubscriptions: activePaid.length,
        freeTrialsCount: freeTrials.length,
        freePlanCount: freePlan.length,
        cancelledCount: cancelled.length,
        pastDueCount: pastDue.length,
        totalMRR,
        totalARR,
        monthlyBillingCount: monthlyCount,
        yearlyBillingCount: yearlyCount,
        failedPaymentsCount: pastDue.length,
      },
      subscriptions: allSubs,
      billingEvents: realBillingEvents,
      revenueByPlan,
      plans: dbPlans,
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to fetch subscriptions' },
      { status: 500 }
    );
  }
}
