import { AmendmentSearchParams } from "@/shared/types/amendment";
import { AmendmentCircuit } from "@/shared/types/ammendment-circuit";
import axiosInstance from "@/utils/axios";
import { create } from "zustand";
import { amendmentEndpoints } from "../endpoints/amendment";
import { circuitEndpoints } from "../endpoints/circuit";

interface AmendmentCircuitStore {
  amendments: AmendmentCircuit[];
  loading: boolean;
  error: string | null;
  totalElements: number;
  getAllAmendments: (params?: AmendmentSearchParams) => Promise<void>;
  exportAmendments: (params: Record<string, any>) => Promise<void>;
}

interface AmendmentApiResponse {
  content: AmendmentCircuit[];
  totalElements: number;
}

export const useAmendmentStore = create<AmendmentCircuitStore>((set: any, get: any) => ({
  amendments: [],
  loading: false,
  error: null,
  totalElements: 0,

  getAllAmendments: async (params: AmendmentSearchParams = {}) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get<AmendmentApiResponse>(
        circuitEndpoints.circuit.ammendment.getAmendments,
        { params }
      );
      set({ amendments: response.data.content, totalElements: response.data.totalElements, loading: false });
    } catch (error: any) {
      console.error('Error fetching amendments:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        headers: error.response?.headers
      });
      set({
        error: error.response?.data?.message || error.message || 'Failed to fetch amendments',
        loading: false
      });
    }
  },

  exportAmendments: async (params: Record<string, any>) => {
    set({ error: null });
    try {
      await axiosInstance.post(
        circuitEndpoints.circuit.ammendment.export,
        null,
        { params }
      );
    } catch (error: any) {
      set({
        error: error.message || "Erreur lors de l'exportation des avenants",
        loading: false,
      });
      throw error;
    }
  }
}));

