import { useMutation, useQueryClient } from '@tanstack/react-query';

import { APIError, errorCauses, fetchAPI } from '@/api';

import { KEY_LIST_MAILBOX } from './useMailboxes';

export interface DisableMailboxParams {
  mailDomainSlug: string;
  mailboxId: string;
  isEnabled: boolean;
}

export interface LoginLinkParams {
  mailDomainSlug: string;
  mailboxId: string;
}

export const loginLink = async ({
  mailDomainSlug,
  mailboxId,
}: LoginLinkParams): Promise<void> => {
  const response = await fetchAPI(
    `mail-domains/${mailDomainSlug}/mailboxes/${mailboxId}/login_link/`,
    {
      method: 'POST',
    },
  );

  if (!response.ok) {
    throw new APIError(
      'Failed to send login link.',
      await errorCauses(response),
    );
  }
};

export const useLoginLink = () => {
  const queryClient = useQueryClient();
  return useMutation<void, APIError, LoginLinkParams>({
    mutationFn: loginLink,
    onSuccess: (_data, variables) => {
      void queryClient.invalidateQueries({
        queryKey: [
          KEY_LIST_MAILBOX,
          { mailDomainSlug: variables.mailDomainSlug },
        ],
      });
    },
  });
};

export const disableMailbox = async ({
  mailDomainSlug,
  mailboxId,
  isEnabled,
}: DisableMailboxParams): Promise<void> => {
  const response = await fetchAPI(
    `mail-domains/${mailDomainSlug}/mailboxes/${mailboxId}/${
      isEnabled ? 'enable' : 'disable'
    }/`,
    {
      method: 'POST',
    },
  );

  if (!response.ok) {
    throw new APIError(
      'Failed to disable the mailbox',
      await errorCauses(response),
    );
  }
};

export const useUpdateMailboxStatus = () => {
  const queryClient = useQueryClient();
  return useMutation<void, APIError, DisableMailboxParams>({
    mutationFn: disableMailbox,
    onSuccess: (_data, variables) => {
      void queryClient.invalidateQueries({
        queryKey: [
          KEY_LIST_MAILBOX,
          { mailDomainSlug: variables.mailDomainSlug },
        ],
      });
    },
  });
};
