import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { APIProductCategoryEntity } from '@/models/api';
import { productCategoriesData } from './data';
import { productsRelatedByCategory } from './[id]/products/data';

const getTypesCount = (categoryId: string) =>
  // @ts-ignore
  productsRelatedByCategory[categoryId]?.length || 0;

const setRelatedLocaleData = (productCategory: APIProductCategoryEntity) => ({
  title: productCategory.fa_title || productCategory.title,
  priceTypeTitle:
    productCategory.fa_priceTypeTitle || productCategory.priceTypeTitle,
  bestForTitle: productCategory.fa_bestForTitle || productCategory.bestForTitle,
  description: productCategory.fa_description || productCategory.description,
});

export async function GET(request: Request) {
  try {
    let data = productCategoriesData as APIProductCategoryEntity[];

    const cookieStore = await cookies();
    const lang = (await cookieStore).get('locale')?.value || 'en';

    data = productCategoriesData.map((productCategory) => ({
      ...productCategory,
      ...(lang === 'fa' ? setRelatedLocaleData(productCategory) : {}),
      typesCount: getTypesCount(productCategory.id),
    }));

    return NextResponse.json({ data });
  } catch (error) {
    console.error('Error fetching product categories:', error);
    return NextResponse.json(
      { error: 'Failed to fetch product categories' },
      { status: 500 },
    );
  }
}
