import { NextResponse } from "next/server";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

export async function GET() {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 15000); // 15 second timeout

    const response = await fetch(`${API_BASE_URL}/fabric-family`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
      },
      next: { revalidate: 300 }, // Cache for 5 minutes
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      return NextResponse.json(
        { success: false, message: "Failed to fetch fabric families" },
        { status: response.status }
      );
    }

    const data = await response.json();
    
    // Transform the response to match the expected format
    if (data.success && data.data && data.data.fabric) {
      return NextResponse.json({
        success: true,
        data: data.data.fabric
      });
    }
    
    return NextResponse.json(data);
  } catch (error: any) {
    console.error("Error in fabric families API:", error);
    return NextResponse.json(
      { success: false, message: error.message || "Internal server error" },
      { status: 500 }
    );
  }
}
