import { create } from 'zustand';
import { endpoints } from '../../endpoints/admin-service';
import axiosInstance from '@/utils/axios';
import { Establishment, EstablishmentPageFilterParams } from '@/shared/types/establishment';


type EstablishmentStore = {
  loading: boolean;
  error: string | null;
  establishments: Establishment[];
  totalElements: number;
  fetchEstablishmentsPage: (params?: EstablishmentPageFilterParams) => Promise<void>;
  toogleActivation: (id: string, isActive: boolean) => Promise<void>;
  establishmentById: Establishment | null;
  getEstablishmentById: (id: string) => Promise<Establishment>;
};

export const useEstablishmentStore = create<EstablishmentStore>((set) => ({
  loading: false,
  error: null,
  establishments: [],
  totalElements: 0,
  fetchEstablishmentsPage: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(endpoints.Admin.Establishment.getEstablishmentsPage, {
        params,
      });

      const { content, totalElements } = response.data;
      set({
        establishments: content,
        totalElements,
        loading: false,
      });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch establishments',
        loading: false,
      });
    }
  },
  toogleActivation: async (id: string, active: boolean) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post<boolean>(endpoints.Admin.Establishment.toggleActivation(id, active));
      set((state) => ({
        establishments: state.establishments.map((establishment) => establishment.id === id ? { ...establishment, active: response.data } : establishment),
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to toggle activation',
        loading: false,
      });
    }
  },
  establishmentById: null,
  getEstablishmentById: async (id: string) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(endpoints.Admin.Establishment.getEstablishmentById(id));
      set({
        establishmentById: response.data,
        loading: false,
      });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to get establishment by id',
        loading: false,
      });
    }
  },
}));