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;
};

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) => {
  const { shiftId, ...payload } = data;
  const response = await apiGlobal.put(`/updateVolunteerShift/${shiftId}`, payload);
  return response;
};
export const fetchVolunteerSlots = async () => {
  const response = await apiGlobal.get(`/fetchVolunteerSlots`);
  return response;
};

export const exportSlotsToCSV = async () => {
  try {
    const response = await apiGlobal.get('/exportSlotsToCSV', {
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'volunteer-slots.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    if (error instanceof AxiosError) {
      console.error('Error exporting slots to CSV:', error.response?.data || error.message);
    } else {
      console.error('Unexpected error exporting slots to CSV:', error);
    }
    throw error;
  }
};
