/**
 * React Query hooks for ticket email settings
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  getTicketEmailSettings,
  updateTicketEmailSettings,
  testImapConnection,
  testSmtpConnection,
  fetchEmailsNow,
  getIncomingEmails,
  reprocessIncomingEmail,
  detectEmailProvider,
  getOAuthStatus,
  initiateGoogleOAuth,
  initiateMicrosoftOAuth,
  getOAuthCredentials,
  deleteOAuthCredential,
  TicketEmailSettings,
  TicketEmailSettingsUpdate,
  IncomingTicketEmail,
  EmailProviderDetectResult,
  OAuthStatusResult,
  OAuthInitiateResult,
  OAuthCredential,
} from '../api/ticketEmailSettings';

const QUERY_KEY = 'ticketEmailSettings';
const INCOMING_EMAILS_KEY = 'incomingTicketEmails';

/**
 * Hook to fetch ticket email settings
 */
export const useTicketEmailSettings = () => {
  return useQuery<TicketEmailSettings>({
    queryKey: [QUERY_KEY],
    queryFn: getTicketEmailSettings,
  });
};

/**
 * Hook to update ticket email settings
 */
export const useUpdateTicketEmailSettings = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: TicketEmailSettingsUpdate) => updateTicketEmailSettings(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
    },
  });
};

/**
 * Hook to test IMAP connection
 */
export const useTestImapConnection = () => {
  return useMutation({
    mutationFn: testImapConnection,
  });
};

/**
 * Hook to test SMTP connection
 */
export const useTestSmtpConnection = () => {
  return useMutation({
    mutationFn: testSmtpConnection,
  });
};

// Legacy alias
export const useTestEmailConnection = useTestImapConnection;

/**
 * Hook to manually fetch emails
 */
export const useFetchEmailsNow = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: fetchEmailsNow,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [INCOMING_EMAILS_KEY] });
    },
  });
};

/**
 * Hook to fetch incoming email audit log
 */
export const useIncomingEmails = (params?: { status?: string; ticket?: number }) => {
  return useQuery<IncomingTicketEmail[]>({
    queryKey: [INCOMING_EMAILS_KEY, params],
    queryFn: () => getIncomingEmails(params),
  });
};

/**
 * Hook to reprocess a failed incoming email
 */
export const useReprocessIncomingEmail = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => reprocessIncomingEmail(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [INCOMING_EMAILS_KEY] });
    },
  });
};

/**
 * Hook to detect email provider from email address
 */
export const useDetectEmailProvider = () => {
  return useMutation({
    mutationFn: (email: string) => detectEmailProvider(email),
  });
};

// OAuth Hooks
const OAUTH_STATUS_KEY = 'oauthStatus';
const OAUTH_CREDENTIALS_KEY = 'oauthCredentials';

/**
 * Hook to get OAuth configuration status
 */
export const useOAuthStatus = () => {
  return useQuery<OAuthStatusResult>({
    queryKey: [OAUTH_STATUS_KEY],
    queryFn: getOAuthStatus,
  });
};

/**
 * Hook to initiate Google OAuth flow
 */
export const useInitiateGoogleOAuth = () => {
  return useMutation({
    mutationFn: (purpose: string = 'email') => initiateGoogleOAuth(purpose),
  });
};

/**
 * Hook to initiate Microsoft OAuth flow
 */
export const useInitiateMicrosoftOAuth = () => {
  return useMutation({
    mutationFn: (purpose: string = 'email') => initiateMicrosoftOAuth(purpose),
  });
};

/**
 * Hook to list OAuth credentials
 */
export const useOAuthCredentials = () => {
  return useQuery<OAuthCredential[]>({
    queryKey: [OAUTH_CREDENTIALS_KEY],
    queryFn: getOAuthCredentials,
  });
};

/**
 * Hook to delete OAuth credential
 */
export const useDeleteOAuthCredential = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => deleteOAuthCredential(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [OAUTH_CREDENTIALS_KEY] });
    },
  });
};

export type {
  TicketEmailSettings,
  TicketEmailSettingsUpdate,
  IncomingTicketEmail,
  EmailProviderDetectResult,
  OAuthStatusResult,
  OAuthInitiateResult,
  OAuthCredential,
};
