import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import {
    AgencyList, AgencyPageFilterParams, AgencyNames, DepartmentNames, LotNumbers, Sector, SectorList, SectorPageFilterParams,
    SectorRequest, AgencyRequest, Agency, SectorNames, Department, DepartmentList, DepartmentPageFilterParams, DepartmentRequest,
    LotList, LotPageFilterParams, Lot, LotRequest
} from '@/shared/types/infrastructure';
import { infrastructureEndpoints } from '../../endpoints/admin-service/infrastructure-endpoints';

type InfrastructureStore = {
    error: string | null;
    loading: boolean;

    clearError: () => void;

    //********* SECTOR *********
    sectorNames: SectorNames[];
    sectorPage: SectorList[];
    sectorPageTotalElements: number;
    lastUsedSectorParams: SectorPageFilterParams | null;
    sectorById: Sector | null;
    existsSectorByNameLoading: boolean;

    fetchSectorNames: () => Promise<void>;
    fetchSectorPage: (params: SectorPageFilterParams) => Promise<void>;
    toggleSectorActivation: (sectorId: string, isActive: boolean) => Promise<void>;
    getSectorById: (sectorId: string) => Promise<Sector | null>;
    createSector: (sector: SectorRequest) => Promise<void>;
    updateSector: (sectorId: string, sector: SectorRequest) => Promise<void>;
    existsSectorByName: (name: string, excludeId?: number) => Promise<boolean>;


    //********* AGENCY *********
    agencyNames: AgencyNames[];
    agencyPage: AgencyList[];
    agencyPageTotalElements: number;
    lastUsedAgencyParams: AgencyPageFilterParams | null;
    agencyById: Agency | null;
    existsAgencyByNameLoading: boolean;
    agencyNameIdByDeparmentIdLoading: boolean;
    errorAgencyNameIdByDeparmentId: string | null;
    agencyNameIdByDeparmentId: AgencyNames | null;

    fetchAgencyNames: () => Promise<void>;
    fetchAgencyPage: (params: AgencyPageFilterParams) => Promise<void>;
    toggleAgencyActivation: (agencyId: string, isActive: boolean) => Promise<void>;
    getAgencyById: (agencyId: string) => Promise<Agency | null>;
    createAgency: (agency: AgencyRequest) => Promise<void>;
    updateAgency: (agencyId: string, agency: AgencyRequest) => Promise<void>;
    existsAgencyByName: (name: string, excludeId?: number) => Promise<boolean>;
    getAgencyNameIdByDepartmentId: (departmentId: number) => Promise<string>;


    //********* DEPARTMENT *********
    departmentNames: DepartmentNames[];
    departmentNamesByAgencyId: DepartmentNames[];
    departmentPage: DepartmentList[];
    departmentPageTotalElements: number;
    lastUsedDepartmentParams: DepartmentPageFilterParams | null;
    departmentById: Department | null;
    existsDepartmentByNameLoading: boolean;
    existsDepartmentByCodeLoading: boolean;
    existsDepartmentByHexColorLoading: boolean;
    departmentHexColorById: string;
    departmentHexColorByName: string;
    departmentNameIdByDeparmentIdLoading: boolean;
    errorDepartmentNameIdByDeparmentId: string | null;
    departmentNameIdByDeparmentId: DepartmentNames | null;

    fetchDepartmentNamesByAgencyId: (agencyId: number) => Promise<void>;
    fetchDepartmentNames: () => Promise<void>;
    fetchDepartmentNamesForRepair: () => Promise<DepartmentNames[]>;
    fetchDepartmentPage: (params: DepartmentPageFilterParams) => Promise<void>;
    toggleDepartmentActivation: (departmentId: string, isActive: boolean) => Promise<void>;
    getDepartmentById: (departmentId: string) => Promise<Department | null>;
    createDepartment: (department: DepartmentRequest) => Promise<void>;
    updateDepartment: (departmentId: string, department: DepartmentRequest) => Promise<void>;
    existsDepartmentByName: (name: string, excludeId?: number) => Promise<boolean>;
    existsDepartmentByCode: (code: string, excludeId?: number) => Promise<boolean>;
    existsDepartmentByHexColor: (hexColor: string, excludeId?: number) => Promise<boolean>;
    getDepartmentHexColorById: (departmentId: string) => Promise<string>;
    getDepartmentHexColorByName: (departmentName: string) => Promise<string>;
    getDepartmentNameIdByDepartmentId: (departmentId: number) => Promise<string>;
    getAllDepartmentColors: () => Promise<string[]>;


    //********* LOT *********
    lotNumbers: LotNumbers[];
    lotPage: LotList[];
    lotPageTotalElements: number;
    lastUsedLotParams: LotPageFilterParams | null;
    lotById: Lot | null;
    existsLotByNumberLoading: boolean;
    lotsNumberIdByDeparmentIdLoading: boolean;
    errorLotsNumberIdByDeparmentId: string | null;
    lotsNumberIdByDeparmentId: LotNumbers[];

    fetchLotNumbers: () => Promise<void>;
    fetchLotPage: (params: LotPageFilterParams) => Promise<void>;
    toggleLotActivation: (lotId: string, isActive: boolean) => Promise<void>;
    getLotById: (lotId: string) => Promise<Lot | null>;
    createLot: (lot: LotRequest) => Promise<void>;
    updateLot: (lotId: string, lot: LotRequest) => Promise<void>;
    existsLotByNumber: (number: string, excludeId?: number) => Promise<boolean>;
    getLotsNumberIdByDepartmentId: (departmentId: number) => Promise<string>;


    //********* Infrasctructure EXPORT *********
    startExportInfrastructureDataInExcel: (params: SectorPageFilterParams) => Promise<void>;
    exportInfrastructureDataInPdf: (params: SectorPageFilterParams) => Promise<void>;
};

export const useInfrastructureStore = create<InfrastructureStore>((set, get) => ({
    error: null,
    loading: false,

    clearError: () => set({ error: null }),

    //********* SECTOR *********
    sectorNames: [],
    fetchSectorNames: async () => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<SectorNames[]>(infrastructureEndpoints.Sector.getSectorNamesAndIds);
            set({ sectorNames: response.data, loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to fetch sector names', loading: false });
        }
    },
    sectorPage: [],
    sectorPageTotalElements: 0,
    lastUsedSectorParams: null,
    fetchSectorPage: async (params) => {
        set({ loading: true, error: null });
        set({ lastUsedSectorParams: params });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Sector.getSectorsPage, {
                params,
            });

            const { content, totalElements } = response.data;
            set({
                sectorPage: content,
                sectorPageTotalElements: totalElements,
                loading: false,
            });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch sectors',
                loading: false,
            });
        }
    },
    toggleSectorActivation: async (sectorId: string, isActive: boolean) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.patch<boolean>(infrastructureEndpoints.Sector.toggleSectorActivation(sectorId, isActive));
            set((state) => ({
                sectorPage: state.sectorPage.map((s) => (s.id === sectorId ? { ...s, active: response.data } : s)),
                loading: false,
            }));
        } catch (error: any) {
            set({ error: error.message || 'Failed to toggle sector active', loading: false });
        }
    },
    sectorById: null,
    getSectorById: async (id) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Sector.getSectorById(id));
            set({ loading: false, sectorById: response.data as Sector });
            return response.data as Sector;
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch sector by ID',
                loading: false,
            });
            return null;
        }
    },
    createSector: async (sector: SectorRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(infrastructureEndpoints.Sector.createSector, sector);
            const { lastUsedSectorParams, fetchSectorPage } = get();
            if (lastUsedSectorParams) {
                await fetchSectorPage(lastUsedSectorParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to create sector', loading: false });
        }
    },
    updateSector: async (sectorId: string, sector: SectorRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(infrastructureEndpoints.Sector.updateSector(sectorId), sector);
            const { lastUsedSectorParams, fetchSectorPage } = get();
            if (lastUsedSectorParams) {
                await fetchSectorPage(lastUsedSectorParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to update sector', loading: false });
        }
    },
    existsSectorByNameLoading: false,
    existsSectorByName: async (name: string, excludeId?: number) => {
        set({ existsSectorByNameLoading: true, error: null });
        try {
            const response = await axiosInstance.get<boolean>(infrastructureEndpoints.Sector.existsSectorByName, {
                params: {
                    name,
                    excludeId
                }
            });
            set({ existsSectorByNameLoading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if sector name exists', existsSectorByNameLoading: false });
            return false;
        }
    },



    //********* AGENCY *********
    agencyNames: [],
    fetchAgencyNames: async () => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<AgencyNames[]>(infrastructureEndpoints.Agency.getAgencyNamesAndIds);
            set({ agencyNames: response.data, loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to fetch agency names', loading: false });
        }
    },
    agencyPage: [],
    agencyPageTotalElements: 0,
    lastUsedAgencyParams: null,
    fetchAgencyPage: async (params) => {
        set({ loading: true, error: null });
        set({ lastUsedAgencyParams: params });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Agency.getAgencyPage, {
                params,
            });
            const { content, totalElements } = response.data;
            set({
                agencyPage: content,
                agencyPageTotalElements: totalElements,
                loading: false,
            });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch agency page',
                loading: false,
            });
        }
    },
    toggleAgencyActivation: async (agencyId: string, isActive: boolean) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.patch<boolean>(infrastructureEndpoints.Agency.toggleAgencyActivation(agencyId, isActive));
            set((state) => ({
                agencyPage: state.agencyPage.map((a) => (a.id === agencyId ? { ...a, active: response.data } : a)),
                loading: false,
            }));
        } catch (error: any) {
            set({ error: error.message || 'Failed to toggle agency active', loading: false });
        }
    },
    agencyById: null,
    getAgencyById: async (id) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Agency.getAgencyById(id));
            set({ loading: false, agencyById: response.data as Agency });
            return response.data as Agency;
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch agency by ID',
                loading: false,
            });
            return null;
        }
    },
    createAgency: async (agency: AgencyRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(infrastructureEndpoints.Agency.createAgency, agency);
            const { lastUsedAgencyParams, fetchAgencyPage } = get();
            if (lastUsedAgencyParams) {
                await fetchAgencyPage(lastUsedAgencyParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to create agency', loading: false });
        }
    },
    updateAgency: async (agencyId: string, agency: AgencyRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(infrastructureEndpoints.Agency.updateAgency(agencyId), agency);
            const { lastUsedAgencyParams, fetchAgencyPage } = get();
            if (lastUsedAgencyParams) {
                await fetchAgencyPage(lastUsedAgencyParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to update agency', loading: false });
        }
    },
    existsAgencyByNameLoading: false,
    existsAgencyByName: async (name: string, excludeId?: number) => {
        set({ existsAgencyByNameLoading: true, error: null });
        try {
            const response = await axiosInstance.get<boolean>(infrastructureEndpoints.Agency.existsAgencyByName, {
                params: {
                    name,
                    excludeId
                }
            });
            set({ existsAgencyByNameLoading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if agency name exists', existsAgencyByNameLoading: false });
            return false;
        }
    },
    agencyNameIdByDeparmentIdLoading: false,
    errorAgencyNameIdByDeparmentId: null,
    agencyNameIdByDeparmentId: null,
    getAgencyNameIdByDepartmentId: async (departmentId: number) => {
        set({ agencyNameIdByDeparmentIdLoading: true, errorAgencyNameIdByDeparmentId: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getParentAgencyByDepartmentId(departmentId));
            set({ agencyNameIdByDeparmentId: response.data, agencyNameIdByDeparmentIdLoading: false });
            return response.data;
        } catch (error: any) {
            set({ errorAgencyNameIdByDeparmentId: error.message || 'Failed to get agency name id by department id', agencyNameIdByDeparmentIdLoading: false });
        }
    },



    //********* DEPARTMENT *********
    departmentNames: [],
    fetchDepartmentNames: async () => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<DepartmentNames[]>(infrastructureEndpoints.Department.getDepartmentNamesAndIds);
            set({ departmentNames: response.data, loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to fetch department names', loading: false });
        }
    },
    fetchDepartmentNamesForRepair: async () : Promise<DepartmentNames[]> => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<DepartmentNames[]>(infrastructureEndpoints.Department.getDepartmentNamesAndIds);
            return response.data
        } catch (error: any) {
            throw error;
        }
    },
    departmentNamesByAgencyId: [],
    fetchDepartmentNamesByAgencyId: async (agencyId: number) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<DepartmentNames[]>(infrastructureEndpoints.Department.getDepartmentNamesAndIdsByAgencyId(agencyId));
            set({ departmentNamesByAgencyId: response.data, loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to fetch department names by agency id', loading: false });
        }
    },
    departmentPage: [],
    departmentPageTotalElements: 0,
    lastUsedDepartmentParams: null,
    fetchDepartmentPage: async (params) => {
        set({ loading: true, error: null });
        set({ lastUsedDepartmentParams: params });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getDepartmentPage, {
                params,
            });
            const { content, totalElements } = response.data;
            set({
                departmentPage: content,
                departmentPageTotalElements: totalElements,
                loading: false,
            });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch department page',
                loading: false,
            });
        }
    },
    toggleDepartmentActivation: async (departmentId: string, isActive: boolean) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.patch<boolean>(infrastructureEndpoints.Department.toggleDepartmentActivation(departmentId, isActive));
            set((state) => ({
                departmentPage: state.departmentPage.map((d) => (d.id === departmentId ? { ...d, active: response.data } : d)),
                loading: false,
            }));
        } catch (error: any) {
            set({ error: error.message || 'Failed to toggle department active', loading: false });
        }
    },
    departmentById: null,
    getDepartmentById: async (id) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getDepartmentById(id));
            set({ loading: false, departmentById: response.data as Department });
            return response.data as Department;
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch department by ID',
                loading: false,
            });
            return null;
        }
    },
    createDepartment: async (department: DepartmentRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(infrastructureEndpoints.Department.createDepartment, department);
            const { lastUsedDepartmentParams, fetchDepartmentPage } = get();
            if (lastUsedDepartmentParams) {
                await fetchDepartmentPage(lastUsedDepartmentParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to create department', loading: false });
        }
    },
    updateDepartment: async (departmentId: string, department: DepartmentRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(infrastructureEndpoints.Department.updateDepartment(departmentId), department);
            const { lastUsedDepartmentParams, fetchDepartmentPage } = get();
            if (lastUsedDepartmentParams) {
                await fetchDepartmentPage(lastUsedDepartmentParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to update department', loading: false });
        }
    },
    existsDepartmentByNameLoading: false,
    existsDepartmentByName: async (name: string, excludeId?: number) => {
        set({ existsDepartmentByNameLoading: true, error: null });
        try {
            const response = await axiosInstance.get<boolean>(infrastructureEndpoints.Department.existsDepartmentByName, {
                params: {
                    name,
                    excludeId
                }
            });
            set({ existsDepartmentByNameLoading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if department name exists', existsDepartmentByNameLoading: false });
            return false;
        }
    },
    existsDepartmentByCodeLoading: false,
    existsDepartmentByCode: async (code: string, excludeId?: number) => {
        set({ existsDepartmentByCodeLoading: true, error: null });
        try {
            const response = await axiosInstance.get<boolean>(infrastructureEndpoints.Department.existsDepartmentByCode, {
                params: {
                    code,
                    excludeId
                }
            });
            set({ existsDepartmentByCodeLoading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if department code exists', existsDepartmentByCodeLoading: false });
            return false;
        }
    },
    existsDepartmentByHexColorLoading: false,
    existsDepartmentByHexColor: async (hexColor: string, excludeId?: number) => {
        set({ existsDepartmentByHexColorLoading: true, error: null });
        try {
            const response = await axiosInstance.get<boolean>(infrastructureEndpoints.Department.existsDepartmentByColor, {
                params: { hexColor, excludeId }
            });
            set({ existsDepartmentByHexColorLoading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if department color exists', existsDepartmentByHexColorLoading: false });
            return false;
        }
    },
    departmentHexColorById: '',
    getDepartmentHexColorById: async (departmentId: string) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getDepartmentHexColorById(departmentId));
            set({ departmentHexColorById: response.data, loading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to get department hex color', loading: false });
            return null;
        }
    },
    departmentHexColorByName: '',
    getDepartmentHexColorByName: async (departmentName: string) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getDepartmentHexColorByName(departmentName));
            set({ departmentHexColorById: response.data, loading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to get department hex color', loading: false });
            return null;
        }
    },
    departmentNameIdByDeparmentIdLoading: false,
    errorDepartmentNameIdByDeparmentId: null,
    departmentNameIdByDeparmentId: null,
    getDepartmentNameIdByDepartmentId: async (departmentId: number) => {
        set({ departmentNameIdByDeparmentIdLoading: true, errorDepartmentNameIdByDeparmentId: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getDepartmentNameIdById(departmentId));
            set({ departmentNameIdByDeparmentId: response.data, departmentNameIdByDeparmentIdLoading: false });
            return response.data;
        } catch (error: any) {
            set({ errorDepartmentNameIdByDeparmentId: error.message || 'Failed to get department name id by department id', departmentNameIdByDeparmentIdLoading: false });
        }
    },
    getAllDepartmentColors: async () => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<string[]>(infrastructureEndpoints.Department.getAllDepartmentColors);
            set({ loading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to get all department colors', loading: false });
            return [];
        }
    },


    //********* LOT *********
    lotNumbers: [],
    fetchLotNumbers: async () => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<LotNumbers[]>(infrastructureEndpoints.Lot.getLotNumbersAndIds);
            set({ lotNumbers: response.data, loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to fetch lot numbers', loading: false });
        }
    },
    lotPage: [],
    lotPageTotalElements: 0,
    lastUsedLotParams: null,
    fetchLotPage: async (params) => {
        set({ loading: true, error: null });
        set({ lastUsedLotParams: params });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Lot.getLotPage, {
                params,
            });
            const { content, totalElements } = response.data;
            set({
                lotPage: content,
                lotPageTotalElements: totalElements,
                loading: false,
            });
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch lot page',
                loading: false,
            });
        }
    },
    toggleLotActivation: async (lotId: string, isActive: boolean) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.patch<boolean>(infrastructureEndpoints.Lot.toggleLotActivation(lotId, isActive));
            set((state) => ({
                lotPage: state.lotPage.map((l) => (l.id === lotId ? { ...l, active: response.data } : l)),
                loading: false,
            }));
        } catch (error: any) {
            set({ error: error.message || 'Failed to toggle lot active', loading: false });
        }
    },
    lotById: null,
    getLotById: async (id) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Lot.getLotById(id));
            set({ loading: false, lotById: response.data as Lot });
            return response.data as Lot;
        } catch (error: any) {
            set({
                error: error.message || 'Failed to fetch lot by ID',
                loading: false,
            });
            return null;
        }
    },
    createLot: async (lot: LotRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(infrastructureEndpoints.Lot.createLot, lot);
            const { lastUsedLotParams, fetchLotPage } = get();
            if (lastUsedLotParams) {
                await fetchLotPage(lastUsedLotParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to create lot', loading: false });
        }
    },
    updateLot: async (lotId: string, lot: LotRequest) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(infrastructureEndpoints.Lot.updateLot(lotId), lot);
            const { lastUsedLotParams, fetchLotPage } = get();
            if (lastUsedLotParams) {
                await fetchLotPage(lastUsedLotParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to update lot', loading: false });
        }
    },
    existsLotByNumberLoading: false,
    existsLotByNumber: async (number: string, excludeId?: number) => {
        set({ existsLotByNumberLoading: true, error: null });
        try {
            const response = await axiosInstance.get<boolean>(infrastructureEndpoints.Lot.existsLotByNumber, {
                params: {
                    number,
                    excludeId
                }
            });
            set({ existsLotByNumberLoading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if lot number exists', existsLotByNumberLoading: false });
            return false;
        }
    },
    lotsNumberIdByDeparmentIdLoading: false,
    errorLotsNumberIdByDeparmentId: null,
    lotsNumberIdByDeparmentId: [],
    getLotsNumberIdByDepartmentId: async (departmentId: number) => {
        set({ lotsNumberIdByDeparmentIdLoading: true, errorLotsNumberIdByDeparmentId: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Department.getLotsByDepartmentId(departmentId));
            set({ lotsNumberIdByDeparmentId: response.data, lotsNumberIdByDeparmentIdLoading: false });
            return response.data;
        } catch (error: any) {
            set({ errorLotsNumberIdByDeparmentId: error.message || 'Failed to get lots number id by department id', lotsNumberIdByDeparmentIdLoading: false });
        }
    },



    //********* EXPORT *********
    startExportInfrastructureDataInExcel: async (params: SectorPageFilterParams) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.post(infrastructureEndpoints.Sector.startExportInfrastructureDataInExcel, null, {
                params,
            });
            set({ loading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to start excel export infrastructure', loading: false });
        }
    },
    exportInfrastructureDataInPdf: async (params: SectorPageFilterParams) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(infrastructureEndpoints.Sector.exportInfrastructureDataInPdf, {
                params,
                responseType: 'blob'
            });
            const blob = new Blob([response.data], { type: 'application/pdf' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'secteurs.pdf');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message || 'Failed to export infrastructure data in pdf', loading: false });
        }
    },
}));