import { NextRequest, NextResponse } from 'next/server';
import { serverApiClient } from '@/utils/serverApiClient';

// Add caching headers for API route
export const revalidate = 600; // Cache for 10 minutes
export const dynamic = 'force-dynamic'; // Mark as dynamic since it uses searchParams

export async function GET(req: NextRequest) {
  try {
    // Forward all accepted query params (including pagination) to backend products2 endpoint
    const query: Record<string, string> = {};
    req.nextUrl.searchParams.forEach((value, key) => {
      if (value !== '') {
        query[key] = value;
      }
    });

    const result = await serverApiClient('products2', {
      method: 'GET',
      query,
    });

    if (!result.success) {
      return NextResponse.json(
        { 
          success: false, 
          message: result.message || 'Failed to fetch products',
          data: { product: [], pagination: null }
        },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      data: result.data,
      message: result.message,
    });
  } catch (error: any) {
    console.error('Error in products API route:', error);
    return NextResponse.json(
      { 
        success: false, 
        message: error.message || 'Internal server error',
        data: { product: [], pagination: null }
      },
      { status: 500 }
    );
  }
}
