import { request } from "./client";

export interface ServerConfig {
  port: number;
  logLevel: string;
  databasePath: string;
  paperlessBaseUrl: string | null;
  paperlessExternalUrl: string | null;
  paperlessConfigured: boolean;
  schedulerIntervalMinutes: number;
  alertDaysBefore: number;
  mailConfigured: boolean;
  mailServer: string | null;
  mailFrom: string | null;
  mailUseTls: boolean;
  ntfyConfigured: boolean;
  authEnabled: boolean;
  authTokenExpiresInHours: number;
}

export async function fetchServerConfig(): Promise<ServerConfig> {
  return request<ServerConfig>("/config", { method: "GET" });
}

export interface SettingsResponse {
  values: {
    paperlessBaseUrl: string | null;
    paperlessExternalUrl: string | null;
    schedulerIntervalMinutes: number;
    alertDaysBefore: number;
    mailServer: string | null;
    mailPort: number | null;
    mailUsername: string | null;
    mailFrom: string | null;
    mailTo: string | null;
    mailUseTls: boolean;
    ntfyServerUrl: string | null;
    ntfyTopic: string | null;
    ntfyPriority: string | null;
    authUsername: string | null;
  };
  secrets: {
    paperlessTokenSet: boolean;
    mailPasswordSet: boolean;
    ntfyTokenSet: boolean;
    authPasswordSet: boolean;
  };
  icalSecret: string | null;
}

export type UpdateSettingsPayload = Partial<{
  paperlessBaseUrl: string | null;
  paperlessExternalUrl: string | null;
  paperlessToken: string | null;
  schedulerIntervalMinutes: number;
  alertDaysBefore: number;
  mailServer: string | null;
  mailPort: number | null;
  mailUsername: string | null;
  mailPassword: string | null;
  mailUseTls: boolean;
  mailFrom: string | null;
  mailTo: string | null;
  ntfyServerUrl: string | null;
  ntfyTopic: string | null;
  ntfyToken: string | null;
  ntfyPriority: string | null;
  authUsername: string | null;
  authPassword: string | null;
  icalSecret: string | null;
}>;

export async function fetchSettings(): Promise<SettingsResponse> {
  return request<SettingsResponse>("/settings", { method: "GET" });
}

export async function updateSettings(payload: UpdateSettingsPayload): Promise<SettingsResponse> {
  return request<SettingsResponse>("/settings", { method: "PUT", body: payload });
}

export async function resetIcalSecret(): Promise<{ icalSecret: string | null }> {
  return request<{ icalSecret: string | null }>("/settings/ical-secret/reset", { method: "POST" });
}

export async function triggerMailTest(): Promise<void> {
  await request("/settings/test/mail", { method: "POST" });
}

export async function triggerNtfyTest(): Promise<void> {
  await request("/settings/test/ntfy", { method: "POST" });
}
