import {
  getApiService,
  getApiServices,
  patchToggleApiService,
  postApiService,
  type CreateApiServiceRequest,
} from "@/api/admin/apiServices";
import type { ApiService, ApiServiceCredentials } from "@/types";
import { create } from "zustand";

interface IAdminState {
  apiServices: ApiService[];
  loadingApiServices: boolean;

  createdCredentials: ApiServiceCredentials | null;
  creatingApiService: boolean;

  viewApiService: ApiService | null;
  fetchingApiService: boolean;

  fetchApiServices: () => Promise<void>;
  fetchApiService: (id: string) => Promise<void>;
  createApiService: (req: CreateApiServiceRequest) => Promise<void>;
  resetCredentials: () => void;

  togglingApiService: boolean;
  toggleApiService: () => Promise<void>;
}

export const useAdmin = create<IAdminState>((set, get) => ({
  apiServices: [],
  loadingApiServices: false,

  createdCredentials: null,
  creatingApiService: false,

  viewApiService: null,
  fetchingApiService: false,

  togglingApiService: false,

  resetCredentials: () => set({ createdCredentials: null }),

  fetchApiServices: async () => {
    set({ loadingApiServices: true });

    try {
      const response = await getApiServices();
      set({ apiServices: response.items });
    } catch (err) {
      console.log("ERR: Failed to fetch services:", err);
    } finally {
      set({ loadingApiServices: false });
    }
  },

  fetchApiService: async (id: string) => {
    set({ fetchingApiService: true });

    try {
      const response = await getApiService(id);
      set({ viewApiService: response });
    } catch (err) {
      console.log("ERR: Failed to fetch services:", err);
    } finally {
      set({ fetchingApiService: false });
    }
  },

  toggleApiService: async () => {
    const viewService = get().viewApiService;
    if (!viewService) return;

    set({ togglingApiService: true });

    try {
      await patchToggleApiService(viewService.id);
      get().fetchApiService(viewService.id);
    } catch (err) {
      console.log("ERR: Failed to toggle service:", err);
    } finally {
      set({ togglingApiService: false });
    }
  },

  createApiService: async (req: CreateApiServiceRequest) => {
    set({ creatingApiService: true });

    try {
      const response = await postApiService(req);
      set({ createdCredentials: response.credentials });
    } catch (err) {
      console.log("ERR: Failed to fetch services:", err);
    } finally {
      set({ creatingApiService: false });
    }
  },
}));
