'use server';
import { safeFetchApi } from '@/lib/fetch.api';
import {
  ApiResponseSchema,
  InventoryTable,
  productMutate,
  productApiResponseSchema,
  getProduct,
  deleteProduct
} from '../schemas/inventory';

export const getInventoryAction = async (params: {
  page?: number;
  limit?: number;
  search?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}) => {

  const searchParams = new URLSearchParams({
    page: (params.page || 1).toString(),
    limit: (params.limit || 10).toString(),
    ...(params.search && { search: params.search }),
    ...(params.sortBy && { sortBy: params.sortBy }),
    ...(params.sortOrder && { sortOrder: params.sortOrder }),
  });

  const [error, response] = await safeFetchApi(
    ApiResponseSchema,
    `/products/inventory?${searchParams}`,
    'GET'
  );

  if (error) {
    console.error(error);
    
    throw new Error(error.message);
  }
  // const transformedData = response?.data ? transformSurvey(response?.data) : undefined;

  return {
    data: response?.data || [],
    meta: response?.meta || {
      page: 1,
      limit: 10,
      totalCount: 0,
      totalPages: 1,
      hasNextPage: false,
      hasPreviousPage: false,
      nextPage: null,
      previousPage: null,
    },
  }
}

export const getAllProducts = async (params: {
  page?: number;
  limit?: number;
  search?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}) => {

  // const session = await auth()

  const searchParams = new URLSearchParams({
    page: (params.page || 1).toString(),
    limit: (params.limit || 10).toString(),
    ...(params.search && { search: params.search  }),
    ...(params.sortBy && { sortBy: params.sortBy }),
    ...(params.sortOrder && { sortOrder: params.sortOrder }),
  })

  // const id = session?.user.id

  const [error, response] = await safeFetchApi(
    productApiResponseSchema,
    `/products/store?${searchParams}`,
    'GET'
  );

  if (error) {
    console.error('Errorrrrr:', error.details);
    throw new Error(error.message);
  }

  return {
    data: response?.data || [],
    meta: response?.meta || {
      page: 1,
      limit: 10,
      totalCount: 0,
      totalPages: 1,
      hasNextPage: false,
      hasPreviousPage: false,
      nextPage: null,
      previousPage: null,
    },
  };
}

export const getProductById = async (id: number) => {
  if (!id) {
    return null;
  }
  const [error, data] = await safeFetchApi(
    getProduct,
    `/products/id/${id}`,
    'GET',
  );

  if (error) {
    if (error.details.status === 404){
      return null
    }
    console.error('❌ Error en la API:', error);
    throw new Error(error.message);
  }

  return data;
}

export const createProductAction = async (payload: FormData) => {
  const [error, data] = await safeFetchApi(
    productMutate,
    '/products',
    'POST',
    payload,
  );

  if (error) {
    console.error(error);
    throw new Error('Error al crear el producto');
  }

  return data;
}

export const updateProductAction = async (payload: InventoryTable) => {
  try { 
    const [error, data] = await safeFetchApi(
      productMutate,
      `/products/upload`,
      'PATCH',
      payload,
    );

    if (error) {
      console.error(error);
      throw new Error(error?.message || 'Error al actualizar el producto');
    }
    console.log(data);
    return data;
    
  } catch (error) {
    console.error(error);
  }
}

export const deleteProductAction = async (id: Number) => {
  if (!id) {
    throw new Error('Error al eliminar el producto')
  }
  const [error] = await safeFetchApi(
    deleteProduct,
    `/products/${id}`,
    'DELETE'
  )
  console.log(error);
  if (error) throw new Error(error.message || 'Error al eliminar el producto')

  return true;
}