import type {
  AcmeCloudflareSettingsDto,
  CertificateIssueJob,
  CertificateIssueRequest,
  CertificateRenewSettingsDto,
  CertificatesListResponse,
} from "@mmapp/contracts/certificates"
import { requestJson } from "@/shared/api/http-client"

export async function listCertificates(baseUrl: string): Promise<CertificatesListResponse> {
  return requestJson<CertificatesListResponse>(baseUrl, "/api/certificates")
}

export async function refreshCertificates(baseUrl: string): Promise<CertificatesListResponse> {
  return requestJson<CertificatesListResponse>(baseUrl, "/api/certificates/refresh", { method: "POST" })
}

export async function createCertificateIssueJob(
  baseUrl: string,
  payload: CertificateIssueRequest,
): Promise<{ jobId: string }> {
  return requestJson<{ jobId: string }>(baseUrl, "/api/certificates/issue", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function getCertificateIssueJob(
  baseUrl: string,
  jobId: string,
): Promise<CertificateIssueJob> {
  return requestJson<CertificateIssueJob>(baseUrl, `/api/certificates/issue/${encodeURIComponent(jobId)}`)
}

export async function getAcmeSettings(baseUrl: string): Promise<AcmeCloudflareSettingsDto> {
  return requestJson<AcmeCloudflareSettingsDto>(baseUrl, "/api/certificates/acme-settings")
}

export async function putAcmeSettings(
  baseUrl: string,
  payload: {
    directoryUrl?: string
    defaultZoneId?: string | null
    cloudflareApiToken?: string | null
  },
): Promise<AcmeCloudflareSettingsDto> {
  return requestJson<AcmeCloudflareSettingsDto>(baseUrl, "/api/certificates/acme-settings", {
    method: "PUT",
    body: JSON.stringify(payload),
  })
}

export async function testAcmeSettings(
  baseUrl: string,
  payload?: { cloudflareApiToken?: string },
): Promise<{ ok: boolean; message?: string }> {
  return requestJson<{ ok: boolean; message?: string }>(baseUrl, "/api/certificates/acme-settings/test", {
    method: "POST",
    body: JSON.stringify(payload ?? {}),
  })
}

export async function getCertificateRenewSettings(baseUrl: string): Promise<CertificateRenewSettingsDto> {
  return requestJson<CertificateRenewSettingsDto>(baseUrl, "/api/certificates/renew-settings")
}

export async function putCertificateRenewSettings(
  baseUrl: string,
  payload: {
    enabled?: boolean
    intervalSec?: number
    renewBeforeDays?: number
  },
): Promise<CertificateRenewSettingsDto> {
  return requestJson<CertificateRenewSettingsDto>(baseUrl, "/api/certificates/renew-settings", {
    method: "PUT",
    body: JSON.stringify(payload),
  })
}
