// @File: src/lib/smtp-settings-api.ts
// @Desc: Thin fetch wrapper around the admin SMTP settings endpoints. The
//        backend is mounted under /api/v1/admin/smtp-settings and protected by
//        the shared get_admin_user dependency, so every request must carry the
//        app JWT we stored in localStorage.token at login time.
export type SmtpEncryption = "NONE" | "TLS" | "SSL";

export interface SmtpSettingsResponse {
  smtp_host: string | null;
  smtp_port: number | null;
  smtp_username: string | null;
  smtp_encryption: SmtpEncryption;
  sender_name: string | null;
  sender_email: string | null;
  reply_to: string | null;
  evt_new_ticket: boolean;
  evt_invoice: boolean;
  evt_service_up: boolean;
  evt_service_down: boolean;
  evt_user_register: boolean;
  evt_payment_fail: boolean;
  has_password: boolean;
}

export interface SmtpSettingsUpdate {
  smtp_host: string | null;
  smtp_port: number | null;
  smtp_username: string | null;
  smtp_password?: string | null; // empty/null means "keep existing"
  smtp_encryption: SmtpEncryption;
  sender_name: string | null;
  sender_email: string | null;
  reply_to: string | null;
  evt_new_ticket: boolean;
  evt_invoice: boolean;
  evt_service_up: boolean;
  evt_service_down: boolean;
  evt_user_register: boolean;
  evt_payment_fail: boolean;
}

const API_BASE = (import.meta.env.VITE_API_BASE_URL || "").replace(/\/$/, "");
const ENDPOINT = `${API_BASE}/api/v1/admin/smtp-settings`;

function authHeaders(): HeadersInit {
  const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
  const headers: Record<string, string> = { "Content-Type": "application/json" };
  if (token) headers.Authorization = `Bearer ${token}`;
  return headers;
}

async function handle<T>(res: Response): Promise<T> {
  if (!res.ok) {
    let detail = `Request failed with status ${res.status}`;
    try {
      const body = await res.json();
      if (body?.detail) detail = typeof body.detail === "string" ? body.detail : JSON.stringify(body.detail);
    } catch {
      /* ignore JSON parse errors */
    }
    throw new Error(detail);
  }
  return res.json() as Promise<T>;
}

export async function fetchSmtpSettings(): Promise<SmtpSettingsResponse> {
  const res = await fetch(ENDPOINT, { method: "GET", headers: authHeaders() });
  return handle<SmtpSettingsResponse>(res);
}

export async function updateSmtpSettings(payload: SmtpSettingsUpdate): Promise<SmtpSettingsResponse> {
  const res = await fetch(ENDPOINT, {
    method: "PUT",
    headers: authHeaders(),
    body: JSON.stringify(payload),
  });
  return handle<SmtpSettingsResponse>(res);
}

export async function sendTestEmail(toEmail: string): Promise<{ success: boolean; message: string }> {
  const res = await fetch(`${ENDPOINT}/test`, {
    method: "POST",
    headers: authHeaders(),
    body: JSON.stringify({ to_email: toEmail }),
  });
  return handle<{ success: boolean; message: string }>(res);
}