import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { BillingService } from '@/lib/shopify/billing';
import { env } from '@/lib/config/env';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const shopDomain = searchParams.get('shop') || env.shopify.defaultShopDomain;
    const shouldSync = searchParams.get('sync') === 'true';

    const [plans, featureDefinitions, allShops] = await Promise.all([
      db.getPlans(),
      db.getFeatureDefinitions(),
      db.getAllShops(),
    ]);

    const resolvedDomain = shopDomain || (allShops[0]?.shopify_domain) || env.shopify.defaultShopDomain;
    let shop = await db.getShopByDomain(resolvedDomain);
    if (!shop && allShops.length > 0) {
      shop = allShops[0];
    }

    if (shouldSync && shop) {
      try {
        await BillingService.syncSubscription(shop.shopify_domain);
        shop = await db.getShopByDomain(shop.shopify_domain);
      } catch (syncErr) {
        console.warn('Sync subscription warning in /api/plans:', syncErr);
      }
    }

    let currentUsage: {
      skuCount: number;
      activePlanId: string;
      planName: string;
      skuLimit: number | null;
      subscriptionStatus: string;
      customLimit?: number | null;
      trialDays?: number;
      trialStartsAt?: string | null;
      trialEndsAt?: string | null;
      trialDaysRemaining?: number | null;
    } = {
      skuCount: 0,
      activePlanId: 'growth',
      planName: 'Growth Plan',
      skuLimit: 10000,
      subscriptionStatus: 'active',
      customLimit: null,
      trialDays: 14,
      trialStartsAt: null,
      trialEndsAt: null,
      trialDaysRemaining: null,
    };

    if (shop) {
      const products = await db.getProducts(shop.id, 100000);
      const activePlan = plans.find((p) => p.id === shop.plan) || plans.find((p) => p.id === 'basic') || plans[0];

      let trialDaysRemaining: number | null = null;
      if (shop.trial_ends_at) {
        const diffMs = new Date(shop.trial_ends_at).getTime() - Date.now();
        trialDaysRemaining = Math.max(0, Math.ceil(diffMs / (1000 * 60 * 60 * 24)));
      }

      currentUsage = {
        skuCount: products.length,
        activePlanId: shop.plan,
        planName: activePlan?.name || 'Growth Plan',
        skuLimit: shop.plan_custom_sku_limit ?? (activePlan ? (activePlan.sku_limit ?? null) : 10000),
        subscriptionStatus: shop.subscription_status || (shop.plan === 'basic' ? 'free' : 'active'),
        customLimit: shop.plan_custom_sku_limit,
        trialDays: shop.trial_days || activePlan?.trial_days || 0,
        trialStartsAt: shop.trial_starts_at || null,
        trialEndsAt: shop.trial_ends_at || null,
        trialDaysRemaining,
      };
    }

    return NextResponse.json({
      success: true,
      plans,
      featureDefinitions,
      shops: allShops.map((s) => ({
        id: s.id,
        domain: s.shopify_domain,
        plan: s.plan,
        status: s.status,
        custom_sku_limit: s.plan_custom_sku_limit,
        trial_days: s.trial_days,
      })),
      shop: shop
        ? {
            id: shop.id,
            domain: shop.shopify_domain,
            plan: shop.plan,
            subscription_status: shop.subscription_status || 'active',
            trial_days: shop.trial_days || 0,
            trial_starts_at: shop.trial_starts_at || null,
            trial_ends_at: shop.trial_ends_at || null,
          }
        : null,
      usage: currentUsage,
    });
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Failed to fetch pricing plans: ' + String(error) },
      { status: 500 }
    );
  }
}
