'use server';
import { safeFetchApi } from '@/lib/fetch.api';
import { trainingStatisticsResponseSchema } from '../schemas/statistics';
import {
  TrainingMutate,
  TrainingSchema,
  trainingApiResponseSchema,
} from '../schemas/training';

export const getTrainingStatisticsAction = async (
  params: {
    startDate?: string;
    endDate?: string;
    stateId?: number;
    municipalityId?: number;
    parishId?: number;
    ospType?: string;
  } = {},
) => {
  const searchParams = new URLSearchParams();
  if (params.startDate) searchParams.append('startDate', params.startDate);
  if (params.endDate) searchParams.append('endDate', params.endDate);
  if (params.stateId) searchParams.append('stateId', params.stateId.toString());
  if (params.municipalityId)
    searchParams.append('municipalityId', params.municipalityId.toString());
  if (params.parishId)
    searchParams.append('parishId', params.parishId.toString());
  if (params.ospType) searchParams.append('ospType', params.ospType);

  const [error, response] = await safeFetchApi(
    trainingStatisticsResponseSchema,
    `/training/statistics?${searchParams.toString()}`,
    'GET',
  );

  if (error) throw new Error(error.message);

  return response?.data;
};

export const getTrainingAction = 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(
    trainingApiResponseSchema,
    `/training?${searchParams}`,
    'GET',
  );

  if (error) 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 createTrainingAction = async (
  payload: TrainingSchema | FormData,
) => {
  let payloadToSend = payload;
  let id: number | undefined;

  if (payload instanceof FormData) {
    payload.delete('id');
    payloadToSend = payload;
  } else {
    const { id: _, ...rest } = payload;
    payloadToSend = rest as any;
  }

  const [error, data] = await safeFetchApi(
    TrainingMutate,
    '/training',
    'POST',
    payloadToSend,
  );

  if (error) {
    throw new Error(error.message || 'Error al crear el registro');
  }

  return data;
};

export const updateTrainingAction = async (
  payload: TrainingSchema | FormData,
) => {
  let id: string | null = null;
  let payloadToSend = payload;

  if (payload instanceof FormData) {
    id = payload.get('id') as string;
    payload.delete('id');
    payloadToSend = payload;
  } else {
    id = payload.id?.toString() || null;
    const { id: _, ...rest } = payload;
    payloadToSend = rest as any;
  }

  if (!id) throw new Error('ID es requerido para actualizar');

  const [error, data] = await safeFetchApi(
    TrainingMutate,
    `/training/${id}`,
    'PATCH',
    payloadToSend,
  );

  if (error) {
    throw new Error(error.message || 'Error al actualizar el registro');
  }

  return data;
};

export const deleteTrainingAction = async (id: number) => {
  const [error] = await safeFetchApi(
    TrainingMutate,
    `/training/${id}`,
    'DELETE',
  );

  if (error) throw new Error(error.message || 'Error al eliminar el registro');

  return true;
};

export const getTrainingByIdAction = async (id: number) => {
  const [error, response] = await safeFetchApi(
    TrainingMutate,
    `/training/${id}`,
    'GET',
  );

  if (error) throw new Error(error.message);

  return response?.data;
};
