import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }

    const metaConn = await db.getMetaConnectionByShopId(shop.id);
    const products = await db.getProductsByShopId(shop.id);
    const latestSync = await db.getLatestSync(shop.id);

    return NextResponse.json({
      success: true,
      shop: {
        id: shop.id,
        domain: shop.shopify_domain,
        status: shop.status,
      },
      meta: {
        connected: metaConn?.status === 'connected',
        catalogId: metaConn?.catalog_id,
        pixelId: metaConn?.pixel_id,
        businessName: metaConn?.business_name,
      },
      stats: {
        productCount: products.length,
        syncedCount: products.filter((p) => p.status === 'synced').length,
        warningCount: products.filter((p) => p.status === 'warning').length,
        errorCount: products.filter((p) => p.status === 'error').length,
      },
      latestSync,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
