import { defineStore } from 'pinia';

import { uzantoByObjIdQuery } from 'src/queries/queries';
import {
  changeAvatar,
  changePassword,
  changeSettings,
  changeTelephoneNumberOrEmail,
} from 'src/queries/mutations';
import { apollo } from 'src/boot/apollo';
import { debugLog } from 'src/utils';
import { useUiStore } from './UI';
import { useCurrentUserStore } from './current-user';

export const useUsersStore = defineStore('users', {
  state: (): UserState => ({
    item: null,
    types: null,
  }),
  getters: {
    getUzanto: (state) => (state.item ? state.item.uzanto : null),
  },

  actions: {
    async executeApolloRequest({ operation, type, variables }) {
      const ui = useUiStore();
      ui.showIsLoading();

      try {
        const response = await apollo.default[type]({
          [type === 'mutate' ? 'mutation' : 'query']: operation,
          variables,
        });
        return response.data;
      } catch (error) {
        console.error(error);
      } finally {
        ui.hideIsLoading();
      }
    },

    setUzanto(payload: any) {
      this.item = payload;
    },
    showLoading() {
      const ui = useUiStore();
      ui.showIsLoading();
    },

    hideLoading() {
      const ui = useUiStore();
      ui.hideIsLoading();
    },

    async fetchUzanto(id) {
      const data = await this.executeApolloRequest({
        operation: uzantoByObjIdQuery,
        type: 'query',
        variables: { id },
      });
      if (data) this.item = data;
    },
    async changeUzanto(payload) {
      const data = await this.executeApolloRequest({
        operation: changeSettings,
        type: 'mutate',
        variables: payload,
      });
      if (data) {
        const auth = useCurrentUserStore();
        auth.getMe(); // Обновление данных текущего пользователя
        return data.aplikiAgordoj;
      }
    },
    async changePassword(
      payload: ChangePasswordPayload,
    ): Promise<ResponseData | void> {
      const auth = useCurrentUserStore();

      const { uzantoId, pasvorto, novaPasvorto } = payload;
      const modifiedPayload = auth.isAdmin
        ? { uzantoId, pasvorto, novaPasvorto }
        : { pasvorto, novaPasvorto };

      const response = await this.executeApolloRequest({
        operation: changePassword,
        type: 'mutate',
        variables: modifiedPayload,
      });

      if (response) {
        const resp: ResponseData = response.shanghiPasvorton;
        if (resp && resp.status) {
          const auth = useCurrentUserStore();
          auth.csrftoken = resp.csrfToken; // Обновление CSRF токена
          return resp;
        }
      }
    },
    async changeTelephoneOrEmail(
      payload: ChangeTelephoneOrEmailPayload,
    ): Promise<ChangeTelephoneOrEmailResponse | void> {
      const response = await this.executeApolloRequest({
        operation: changeTelephoneNumberOrEmail,
        type: 'mutate',
        variables: payload,
      });

      if (response) {
        const resp: ChangeTelephoneOrEmailResponse =
          response.shanghiPoshtonTelefonon;
        if (resp && resp.status) {
          // Здесь можно добавить любую дополнительную логику, например, обновление данных пользователя
          return resp;
        }
      }
    },

    async changeAvatar(
      payload: ChangeAvatarPayload,
    ): Promise<ChangeAvatarResponse | void> {
      const response = await this.executeApolloRequest({
        operation: changeAvatar,
        type: 'mutate',
        variables: payload,
      });

      if (response) {
        const resp: ChangeAvatarResponse = response.instaliAvataron;
        if (resp && resp.status) {
          // Здесь можно добавить логику обновления URL аватара в пользовательском профиле
          return resp;
        }
      }
    },
  },
});
