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

// Enable edge runtime for faster response times
export const runtime = 'nodejs';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    
    // Build query object from search params
    const query: Record<string, string> = {};
    const q = searchParams.get('q');
    const color = searchParams.get('color');
    const category = searchParams.get('category');
    const finish = searchParams.get('finish');
    const gsm = searchParams.get('gsm');
    const seasonality = searchParams.get('seasonality');

    if (q) query.q = q;
    if (color) query.color = color;
    if (category) query.category = category;
    if (finish) query.finish = finish;
    if (gsm) query.gsm = gsm;
    if (seasonality) query.seasonality = seasonality;

    // Fetch fabric data from backend API with extended cache
    const response = await serverApiClient('library/fabric', {
      query,
      revalidate: 300, // Cache for 5 minutes
    });

    if (!response.success) {
      return NextResponse.json(
        { 
          success: false, 
          message: response.message || 'Failed to fetch fabric data' 
        },
        { 
          status: 404,
          headers: {
            'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=30',
          },
        }
      );
    }

    return NextResponse.json(
      { data: response.data },
      {
        headers: {
          // AWS Amplify CDN caching headers
          'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600',
          'CDN-Cache-Control': 'public, s-maxage=300',
          'Vercel-CDN-Cache-Control': 'public, s-maxage=300',
        },
      }
    );
  } catch (error: any) {
    console.error('Error in fabric library API:', error);
    return NextResponse.json(
      { 
        success: false, 
        message: error.message || 'Internal server error' 
      },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'public, s-maxage=10, stale-while-revalidate=30',
        },
      }
    );
  }
}
