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

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const search = (searchParams.get('search') || '').toLowerCase().trim();
    const planFilter = searchParams.get('plan') || 'ALL';
    const statusFilter = searchParams.get('status') || 'ALL';

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

    // Enrich each shop with live statistics
    const storesData = await Promise.all(
      allShops.map(async (shop) => {
        let metaConn = null;
        let pixelsCount = 0;
        let productsCount = 0;
        let eventsCount = 0;

        try {
          metaConn = await db.getMetaConnectionByShopId(shop.id);
        } catch {}

        try {
          const pixels = await db.getPixelsByShopId(shop.id);
          pixelsCount = pixels.length;
        } catch {}

        try {
          const products = await db.getProductsByShopId(shop.id);
          productsCount = products.length;
        } catch {}

        try {
          const events = await db.getCapiEvents(shop.id, 100);
          eventsCount = events.length;
        } catch {}

        // Match price from dbPlans
        const planObj = dbPlans.find((p) => p.id.toLowerCase() === (shop.plan || 'basic').toLowerCase());
        const monthlyPrice = planObj ? planObj.price : shop.plan === 'accelerate' ? 99 : shop.plan === 'growth' ? 13 : 0;

        return {
          id: shop.id,
          shopify_domain: shop.shopify_domain,
          shopify_shop_id: shop.shopify_shop_id || null,
          status: shop.status || 'installed',
          plan: shop.plan || 'growth',
          plan_price: monthlyPrice,
          plan_name: planObj ? planObj.name : `${(shop.plan || 'growth').toUpperCase()} Plan`,
          subscription_status: shop.subscription_status || (monthlyPrice > 0 ? 'active' : 'free'),
          installed_at: shop.installed_at || shop.created_at || new Date().toISOString(),
          created_at: shop.created_at,
          updated_at: shop.updated_at,
          meta: {
            connected: Boolean(metaConn),
            business_name: metaConn?.business_name || null,
            pixel_name: metaConn?.pixel_name || null,
            pixel_id: metaConn?.pixel_id || null,
            catalog_name: metaConn?.catalog_name || null,
          },
          stats: {
            productsCount,
            pixelsCount,
            eventsCount,
          },
        };
      })
    );

    // Apply filtering
    let filteredStores = storesData.filter((store) => {
      const matchesSearch =
        !search ||
        store.shopify_domain.toLowerCase().includes(search) ||
        store.id.toLowerCase().includes(search) ||
        (store.meta.business_name && store.meta.business_name.toLowerCase().includes(search));

      const matchesPlan =
        planFilter === 'ALL' || store.plan.toLowerCase() === planFilter.toLowerCase();

      const matchesStatus =
        statusFilter === 'ALL' || store.status.toLowerCase() === statusFilter.toLowerCase();

      return matchesSearch && matchesPlan && matchesStatus;
    });

    // Compute SaaS Global Metrics
    const totalStores = storesData.length;
    const installedStores = storesData.filter((s) => s.status === 'installed').length;
    const uninstalledStores = storesData.filter((s) => s.status === 'uninstalled').length;

    const totalMRR = storesData
      .filter((s) => s.status === 'installed')
      .reduce((sum, s) => sum + s.plan_price, 0);

    const totalSyncedProducts = storesData.reduce((sum, s) => sum + s.stats.productsCount, 0);
    const totalCapiEvents = storesData.reduce((sum, s) => sum + s.stats.eventsCount, 0);

    const planBreakdown = {
      basic: storesData.filter((s) => s.plan === 'basic').length,
      growth: storesData.filter((s) => s.plan === 'growth').length,
      accelerate: storesData.filter((s) => s.plan === 'accelerate').length,
      custom: storesData.filter((s) => !['basic', 'growth', 'accelerate'].includes(s.plan)).length,
    };

    return NextResponse.json({
      success: true,
      metrics: {
        totalStores,
        installedStores,
        uninstalledStores,
        totalMRR,
        totalSyncedProducts,
        totalCapiEvents,
        planBreakdown,
      },
      stores: filteredStores,
      availablePlans: dbPlans.map((p) => ({
        id: p.id,
        name: p.name,
        price: p.price,
        sku_limit: p.sku_limit,
      })),
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Failed to fetch SaaS admin data' },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { action, shopId, newPlan } = body;

    if (action === 'update_plan') {
      if (!shopId || !newPlan) {
        return NextResponse.json({ success: false, error: 'shopId and newPlan are required' }, { status: 400 });
      }

      const shop = await db.getShopById(shopId);
      if (!shop) {
        return NextResponse.json({ success: false, error: 'Shop not found' }, { status: 404 });
      }

      await db.updateShopPlan(shopId, newPlan.toLowerCase());

      return NextResponse.json({
        success: true,
        message: `Updated plan for ${shop.shopify_domain} to ${newPlan.toUpperCase()}`,
      });
    }

    return NextResponse.json({ success: false, error: 'Unsupported action' }, { status: 400 });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Action failed' },
      { status: 500 }
    );
  }
}
