import { NextRequest, NextResponse } from 'next/server';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';
import { ShopifyProductService } from '@/lib/shopify/product-service';

export const dynamic = 'force-dynamic';

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

    const query = searchParams.get('q') || searchParams.get('query') || '';
    const page = parseInt(searchParams.get('page') || '1', 10);
    const limit = parseInt(searchParams.get('limit') || '20', 10);

    const result = await ShopifyProductService.fetchProductsPaginated({
      shopDomain: shop.shopify_domain,
      query,
      page,
      limit,
    });

    return NextResponse.json({
      success: true,
      products: result.products,
      pagination: result.pagination,
    });
  } catch (err: any) {
    console.error('[API /api/shopify/products GET] Error:', err);
    return NextResponse.json(
      { success: false, error: err.message || 'Failed to fetch Shopify products' },
      { status: 500 }
    );
  }
}
