// ─────────────────────────────────────────────────────────────────────────────
// email-settings.api.ts
// API client for the Email Settings module.
// Uses the shared fetchApi helper (same as inquiry.api.ts).
// ─────────────────────────────────────────────────────────────────────────────

import { fetchApi } from "@/lib/api/http";
import type {
  EmailSetting,
  UpsertEmailSettingDto,
  SendTestDto,
} from "@/lib/api/types/email-settings.types";

// Base URL — strip a trailing /api the same way the other modules do, then re-add.
export const EMAIL_SETTINGS_API_BASE =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

const ROOT = `${EMAIL_SETTINGS_API_BASE}/email-settings`;

// ─── List all configs ────────────────────────────────────────────────────────
export function getEmailSettings(): Promise<EmailSetting[]> {
  return fetchApi<EmailSetting[]>(ROOT);
}

// ─── Get one config ──────────────────────────────────────────────────────────
export function getEmailSetting(id: number): Promise<EmailSetting> {
  return fetchApi<EmailSetting>(`${ROOT}/${id}`);
}

// ─── Create ──────────────────────────────────────────────────────────────────
export function createEmailSetting(
  dto: UpsertEmailSettingDto,
): Promise<EmailSetting> {
  return fetchApi<EmailSetting>(ROOT, {
    method: "POST",
    body: JSON.stringify(dto),
  });
}

// ─── Update ──────────────────────────────────────────────────────────────────
export function updateEmailSetting(
  id: number,
  dto: UpsertEmailSettingDto,
): Promise<EmailSetting> {
  return fetchApi<EmailSetting>(`${ROOT}/${id}`, {
    method: "PUT",
    body: JSON.stringify(dto),
  });
}

// ─── Delete ──────────────────────────────────────────────────────────────────
export function deleteEmailSetting(id: number): Promise<{ ok: boolean }> {
  return fetchApi<{ ok: boolean }>(`${ROOT}/${id}`, { method: "DELETE" });
}

// ─── Send a test email from this config ──────────────────────────────────────
// NOTE: id here is the CONFIG ROW id, not the user_id.
export function sendTestEmail(
  id: number,
  dto: SendTestDto,
): Promise<{ ok: boolean }> {
  return fetchApi<{ ok: boolean }>(`${ROOT}/${id}/test`, {
    method: "POST",
    body: JSON.stringify(dto),
  });
}
