import { defineStore } from "pinia";
import { useMainStore } from "./main";
import type { IUserProfileCreate, IUserProfile, IUserProfileUpdate } from "@/interfaces";
import { api } from "@/api";


interface AdminState {
  users: IUserProfile[];
}

const defaultState: AdminState = {
  users: [],
};
  
export const useAdminStore = defineStore("AdminStoreId", {
  state: () => defaultState,
  getters: {
      readAdminUsers: (state) => state.users,
      readAdminOneUser: (state) => {
        return (userId:number) => state.users.filter((user) => user.id === userId)[0] || undefined;
      },
  },
  actions: {
      // setters
      setUsers(payload: IUserProfile[]) {
        this.users = payload;
      },
      setUser(payload: IUserProfile) {
        const users = this.users.filter((user: IUserProfile) => user.id !== payload.id);
        users.push(payload);
        this.users = users;
      },
      
      // actions
      async actionGetUsers(){
        const mainStore = useMainStore();
        try {
          const response = await api.getUsers(mainStore.token)
          if (response) {
            this.setUsers(response.data);
          }
        } catch (error) {
          await mainStore.checkApiError(error);
        }
      },
      async actionUpdateUser(payload: { id: number; user: IUserProfileUpdate }) {
        const mainStore = useMainStore();
        try {
          const loadingNotification = { content: "saving", showProgress: true };
          mainStore.addNotification(loadingNotification);
          const response = (
            await Promise.all([
              api.updateUser(mainStore.token, payload.id, payload.user),
              await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
            ])
          )[0];
          this.setUser(response.data);
          mainStore.removeNotification(loadingNotification);
          mainStore.addNotification({
            content: "User successfully updated",
            color: "success",
          });
        } catch (error) {
          await mainStore.checkApiError(error);
        }
      },
      async actionCreateUser(payload: IUserProfileCreate) {
        const mainStore = useMainStore();
        try {
          const loadingNotification = { content: "saving", showProgress: true };
          mainStore.addNotification(loadingNotification);
          const response = (
            await Promise.all([
              api.createUser(mainStore.token, payload),
              await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
            ])
          )[0];
          this.setUser(response.data);
          mainStore.removeNotification(loadingNotification);
          mainStore.addNotification({
            content: "User successfully created",
            color: "success",
          });
        } catch (error) {
          await mainStore.checkApiError(error);
        }
      },
      async actionTestCeleryMsg(payload: {msg:string}) {
        const mainStore = useMainStore();
        try {
          const loadingNotification = { content: "sending", showProgress: true };
          mainStore.addNotification(loadingNotification);
          const response = (
            await Promise.all([
              api.testCeleryMsg(mainStore.token, payload),
              await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
            ])
          );
          mainStore.removeNotification(loadingNotification);
          mainStore.addNotification({
            content: "Word received",
              color: "success",
          })
        } catch (error) {
          await mainStore.checkApiError(error);
        }
      },
      async actionTestCeleryFile(payload: File) {
        const mainStore = useMainStore();
        try {
          const loadingNotification = { content: "sending", showProgress: true };
          mainStore.addNotification(loadingNotification);
          const response = (
            await Promise.all([
              api.testCeleryFile(mainStore.token, payload),
              await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
            ])
          );
          mainStore.removeNotification(loadingNotification);
          mainStore.addNotification({
            content: "File received",
              color: "success",
          })
        } catch (error) {
          await mainStore.checkApiError(error);
        }
      }
  },
});