import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { roadMapEndpoints } from '../endpoints/roadMap';
import { DriverInfoDTO, WorkedDayDTO } from '@/shared/types/driver-roadmap';


type WorkedDayStore = {
  driverInfo: DriverInfoDTO | null;
  workedDay: WorkedDayDTO | null;
  loading: boolean;
  error: string | null;
  getDriverInfos: (driverId: number) => Promise<void>;
  getWorkedDay: (driverRoadMapId: number, date: string) => Promise<WorkedDayDTO>;
  submitWorkedDay: (payload: WorkedDayDTO) => Promise<void>;
};

export const useWorkedDayStore = create<WorkedDayStore>((set) => ({
  driverInfo: null,
  workedDay: null,
  loading: false,
  error: null,

  getDriverInfos: async (driverId: number) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.workedDay.getDriverInfo(driverId)
      );
      set({ driverInfo: response.data, loading: false });
    } catch (error: any) {
      set({
        error: error.message || 'Erreur lors de la récupération des infos conducteur',
        loading: false,
      });
    }
  },

  getWorkedDay: async (driverRoadMapId: number, date: string): Promise<WorkedDayDTO> => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(
        roadMapEndpoints.workedDay.getByDate,
        {
          params: { driverRoadMapId, date },
        }
      );
      set({ workedDay: response.data, loading: false });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Erreur lors de la récupération du WorkedDay',
        loading: false,
      });
      throw error;
    }
  },

  submitWorkedDay: async (payload: WorkedDayDTO) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post(
        roadMapEndpoints.workedDay.createOrUpdate,
        payload
      );
      set({ loading: false });
    } catch (error: any) {
      console.error("API Error:", error);
      set({
        error:
          error.response?.data?.message || 'Erreur lors de la soumission du WorkedDay',
        loading: false,
      });
      throw error;
    }
  }


}));
