'use server';

import type { IProductCategoryCardProps } from '@/components/pages/productCategories/productCategoryCard.d';
import type { IProductCardProps } from '@/components/pages/products/productCard/productCard.d';
import api from '@/lib/axios';
import { IResponse } from '@/models/response';
import { cookies } from 'next/headers';

export async function getProductCategories() {
  const cookiesStore = await cookies();
  return api
    .get('/product_categories', {
      headers: {
        Cookie: cookiesStore.toString(),
      },
    })
    .then(({ data }) => {
      return Promise.resolve(data.data);
    })
    .catch((error) => Promise.reject(error));
}

export async function getProductCategoryById(
  categoryId: string,
): Promise<IProductCategoryCardProps> {
  const cookiesStore = await cookies();
  return api
    .get(`/product_categories/${categoryId}`, {
      headers: {
        Cookie: cookiesStore.toString(),
      },
    })
    .then(({ data }) => {
      return Promise.resolve(data.data);
    })
    .catch((error) => Promise.reject(error));
}

export async function getProducts(
  categoryId: string,
  page = 1,
): Promise<IResponse<IProductCardProps[]>> {
  const cookiesStore = await cookies();
  console.log('request');
  console.log(page);

  return api
    .get(`/product_categories/${categoryId}/products`, {
      headers: {
        Cookie: cookiesStore.toString(),
      },
      params: { page },
    })
    .then(({ data }) => {
      return Promise.resolve(data);
    })
    .catch((error) => Promise.reject(error));
}
