import apiGlobal from '@/services/apiGlobal';
import axios, { AxiosError } from 'axios';

export const createVolunteerSlot = async ({ numberOfSlots, slotName }: { numberOfSlots: number; slotName: string }) => {
  const response = await apiGlobal.post(`/createVolunteerSlot`, {
    numberOfSlots,
    slotName,
  });
  return response;
};
export const updateVolunteerSlot = async (
  id: string,
  { numberOfSlots, slotName }: { numberOfSlots: number; slotName: string }
) => {
  const response = await apiGlobal.put(`/updateVolunteerSlot/${id}`, {
    numberOfSlots,
    slotName,
  });
  return response;
};

interface ICreateVolunteerShift {
  shiftDate: string;
  shiftStartTime: string;
  shiftEndTime: string;
  slotId: string;
  address: string;
}

export const createVolunteerShift = async (data: ICreateVolunteerShift[]) => {
  const response = await apiGlobal.post(`/createVolunteerShift`, data);
  return response;
};

interface IUpdateVolunteerShift {
  shiftId: string;
  shiftDate?: string;
  shiftStartTime?: string;
  shiftEndTime?: string;
  slotId?: string;
  address?: string;
}

export const updateVolunteerShift = async (data: IUpdateVolunteerShift) => {
  try {
    const { shiftId, ...payload } = data;
    
    if (!shiftId) {
      throw new Error('Shift ID is required for updating volunteer shift');
    }
    
    const response = await apiGlobal.put(`/updateVolunteerShift/${shiftId}`, payload);
    return response;
  } catch (error) {
    if (error instanceof AxiosError) {
      console.error('Error updating volunteer shift:', error.response?.data || error.message);
    } else {
      console.error('Unexpected error updating volunteer shift:', error);
    }
    throw error;
  }
};

export const fetchVolunteerShifts = async () => {
  try {
    const response = await apiGlobal.get(`/fetchVolunteerShifts`);
    return response;
  } catch (error) {
    if (error instanceof AxiosError) {
      console.error('Error fetching volunteer shifts:', error.response?.data || error.message);
    } else {
      console.error('Unexpected error fetching volunteer shifts:', error);
    }
    throw error;
  }
};
