import {
  adminGetUserApi,
  adminGetUsersApi,
  postUser,
  type CreateUserRequest,
} from "@/api/admin/users";
import type { UserProfile } from "@/types";
import { create } from "zustand";

export interface IUsersState {
  users: UserProfile[];
  fetching: boolean;

  current: UserProfile | null;
  fetchingCurrent: boolean;

  creating: boolean;
  createUser: (req: CreateUserRequest) => Promise<void>;

  fetchUsers: () => Promise<void>;
  fetchUser: (id: string) => Promise<void>;
}

export const useUsers = create<IUsersState>((set) => ({
  users: [],
  fetching: false,

  creating: false,

  current: null,
  fetchingCurrent: false,

  createUser: async (req: CreateUserRequest) => {
    set({ creating: true });

    try {
      const response = await postUser(req);
      console.log("INFO: User has been created:", response);
    } catch (err) {
      console.log("ERR: Failed to create user:", err);
    } finally {
      set({ creating: false });
    }
  },

  fetchUsers: async () => {
    set({ fetching: true });

    try {
      const response = await adminGetUsersApi();
      set({ users: response.items ?? [] });
    } catch (err) {
      console.log("ERR: Failed to fetch users for admin:", err);
    } finally {
      set({ fetching: false });
    }
  },

  fetchUser: async (id: string) => {
    set({ fetchingCurrent: true });

    try {
      const response = await adminGetUserApi(id);
      set({ current: response });
    } catch (err) {
      console.log("ERR: Failed to fetch single user for admin:", err);
    } finally {
      set({ fetchingCurrent: false });
    }
  },
}));
