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

// Cache fabric family data for 15 minutes
export const revalidate = 900;

/**
 * Get fabric family details with filtering
 * Cached server-side to reduce costs on AWS Amplify
 */
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const { slug } = await params;
    const searchParams = req.nextUrl.searchParams;
    
    // Build query string
    const queryParams = new URLSearchParams();
    const gsm = searchParams.get('gsm');
    const finished = searchParams.get('finished');
    const ideaFor = searchParams.get('ideaFor');
    const color = searchParams.get('color');
    const q = searchParams.get('q');
    const hasFilterClick = searchParams.get('hasFilterClick');
    
    if (gsm) queryParams.append('gsm', gsm);
    if (finished) queryParams.append('finished', finished);
    if (ideaFor) queryParams.append('ideaFor', ideaFor);
    if (color) queryParams.append('color', color);
    if (q) queryParams.append('q', q);
    if (hasFilterClick) queryParams.append('hasFilterClick', hasFilterClick);

    const endpoint = `fabric-list-by-family/${slug}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
    
    const result = await serverApiClient(endpoint, {
      method: 'GET',
      revalidate: 900, // Cache for 15 minutes
    });

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

    return NextResponse.json(
      {
        success: true,
        data: result.data,
      },
      {
        headers: {
          'Cache-Control': 'public, s-maxage=900, stale-while-revalidate=1800',
        },
      }
    );
  } catch (error: any) {
    console.error('Error fetching fabric family data:', error);
    return NextResponse.json(
      {
        success: false,
        message: error.message || 'Failed to fetch fabric data',
        data: { fabric: [], tag: [], products: [], family: null }
      },
      { status: 500 }
    );
  }
}
