import { apiClient } from '@/lib/api-client';
import type {
  EmailConfigurationPayload,
  EmailConfigurationSummary,
  EmailConnectionTestResult,
  SendTestEmailPayload,
  SendTestEmailResult,
} from './types';

const EMAIL_CONFIG_ENDPOINT = '/notifications/email-configurations';

export async function listEmailConfigurations(): Promise<EmailConfigurationSummary[]> {
  return apiClient<EmailConfigurationSummary[]>(EMAIL_CONFIG_ENDPOINT);
}

export async function createEmailConfiguration(
  payload: EmailConfigurationPayload
): Promise<EmailConfigurationSummary> {
  return apiClient<EmailConfigurationSummary>(EMAIL_CONFIG_ENDPOINT, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(payload),
  });
}

export async function updateEmailConfiguration(
  id: string,
  payload: EmailConfigurationPayload
): Promise<EmailConfigurationSummary> {
  return apiClient<EmailConfigurationSummary>(`${EMAIL_CONFIG_ENDPOINT}/${id}`, {
    method: 'PATCH',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(payload),
  });
}

export async function deleteEmailConfiguration(id: string): Promise<{ success: true }> {
  return apiClient<{ success: true }>(`${EMAIL_CONFIG_ENDPOINT}/${id}`, {
    method: 'DELETE',
  });
}

export async function testEmailConfigurationConnection(
  id: string
): Promise<EmailConnectionTestResult> {
  return apiClient<EmailConnectionTestResult>(`${EMAIL_CONFIG_ENDPOINT}/${id}/test`, {
    method: 'POST',
  });
}

export async function sendEmailConfigurationTestEmail(
  id: string,
  payload: SendTestEmailPayload
): Promise<SendTestEmailResult> {
  return apiClient<SendTestEmailResult>(`${EMAIL_CONFIG_ENDPOINT}/${id}/send-test`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(payload),
  });
}
