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();
    }

    // Strictly fetch products belonging to this authenticated shop
    const products = await db.getProductsByShopId(shop.id);
    const latestSync = await db.getLatestSync(shop.id);

    return NextResponse.json({
      success: true,
      shopDomain: shop.shopify_domain,
      totalCount: products.length,
      latestSync,
      products,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
