import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from './client';

export interface EmailConnectorResponse {
  connectorId: string;
  factoryId: string;
  host: string;
  port: number;
  username: string;
  fromEmail: string;
  registrationEnabled: boolean;
}

export interface SmtpConfigRequest {
  host: string;
  port: number;
  username: string;
  password: string;
  fromEmail: string;
  registrationEnabled?: boolean;
}

export interface TestEmailResult {
  status: string;
  message: string;
}

export function useEmailConnector() {
  return useQuery<EmailConnectorResponse | null>({
    queryKey: ['vendor', 'email-connector'],
    queryFn: async () => {
      try {
        return await api.get<EmailConnectorResponse>('/vendor/email-connector');
      } catch (e) {
        if (e instanceof Error && e.message.includes('404')) return null;
        throw e;
      }
    },
  });
}

export function useSaveEmailConnector() {
  const qc = useQueryClient();
  return useMutation<EmailConnectorResponse, Error, SmtpConfigRequest>({
    mutationFn: (config) => api.post('/vendor/email-connector', config),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'email-connector'] }),
  });
}

export function useDeleteEmailConnector() {
  const qc = useQueryClient();
  return useMutation<void, Error, void>({
    mutationFn: () => api.delete('/vendor/email-connector'),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'email-connector'] }),
  });
}

export function useTestEmailConnector() {
  return useMutation<TestEmailResult, Error, string>({
    mutationFn: (to) => api.post('/vendor/email-connector/test', { to }),
  });
}

export function useToggleRegistration() {
  const qc = useQueryClient();
  return useMutation<void, Error, boolean>({
    mutationFn: (enabled) => api.post('/vendor/email-connector/registration', { enabled }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['vendor', 'email-connector'] }),
  });
}
