import * as acme from "acme-client"
import type { Server } from "../db/schema.js"
import {
  getAcmeAccountPrivateKey,
  getAcmeCloudflareToken,
  getAcmeSettingsPublic,
  saveAcmeAccountPrivateKey,
} from "./certificates-service.js"
import { MikrotikClient } from "./mikrotik.js"

type CfResponse<T> = { success: boolean; errors?: Array<{ message?: string }>; result?: T }

async function cloudflareRequest<T>(
  token: string,
  path: string,
  init?: RequestInit,
): Promise<T> {
  const headers: Record<string, string> = {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  }
  const res = await fetch(`https://api.cloudflare.com/client/v4${path}`, {
    ...init,
    headers,
  })
  const json = (await res.json()) as CfResponse<T>
  if (!res.ok || !json.success) {
    const msg = json.errors?.map((e) => e.message).filter(Boolean).join("; ")
      || `Cloudflare API HTTP ${res.status}`
    throw new Error(msg)
  }
  return json.result as T
}

export async function testCloudflareToken(token: string): Promise<void> {
  await cloudflareRequest<Array<{ id: string; name: string }>>(token, "/zones?per_page=1")
}

async function resolveZoneId(token: string, domain: string, defaultZoneId?: string): Promise<string> {
  const labels = domain.split(".").filter(Boolean)
  for (let i = 0; i < labels.length - 1; i++) {
    const guess = labels.slice(i).join(".")
    const zones = await cloudflareRequest<Array<{ id: string; name: string }>>(
      token,
      `/zones?name=${encodeURIComponent(guess)}`,
    )
    if (zones[0]?.id) return zones[0].id
  }
  if (defaultZoneId?.trim()) return defaultZoneId.trim()
  throw new Error(`Не удалось определить зону Cloudflare для ${domain}`)
}

async function createTxtRecord(
  token: string,
  zoneId: string,
  recordName: string,
  value: string,
): Promise<string> {
  const created = await cloudflareRequest<{ id: string }>(token, `/zones/${zoneId}/dns_records`, {
    method: "POST",
    body: JSON.stringify({
      type: "TXT",
      name: recordName,
      content: value,
      ttl: 120,
    }),
  })
  return created.id
}

async function deleteTxtRecord(token: string, zoneId: string, recordId: string): Promise<void> {
  await cloudflareRequest(token, `/zones/${zoneId}/dns_records/${recordId}`, { method: "DELETE" })
}

async function sleep(ms: number) {
  await new Promise((resolve) => setTimeout(resolve, ms))
}

async function getOrCreateAccountKey(): Promise<Buffer> {
  const existing = getAcmeAccountPrivateKey()
  if (existing) return Buffer.from(existing)
  const key = await acme.crypto.createPrivateKey()
  saveAcmeAccountPrivateKey(key.toString("utf8"))
  return key
}

async function ensureAcmeAccount(client: acme.Client): Promise<void> {
  try {
    client.getAccountUrl()
    return
  } catch {
    await client.createAccount({ termsOfServiceAgreed: true })
  }
}

export async function issueCertificateWithCloudflareDns(params: {
  server: Server
  certName: string
  domainNames: string[]
  keyType: "rsa2048" | "ec256"
  trustStore: string[]
  onStep?: (step: string) => void
}): Promise<void> {
  const settings = getAcmeSettingsPublic()
  const token = getAcmeCloudflareToken()
  if (!token) throw new Error("Не настроен Cloudflare API token")

  const domains = [...new Set(params.domainNames.map((d) => d.trim().toLowerCase()).filter(Boolean))]
  if (domains.length === 0) throw new Error("Нужен хотя бы один домен")

  params.onStep?.("acme_order")
  const accountKey = await getOrCreateAccountKey()
  const client = new acme.Client({
    directoryUrl: settings.directoryUrl,
    accountKey,
  })
  await ensureAcmeAccount(client)

  const altNames = domains.slice(1)
  const privateKey = params.keyType === "ec256"
    ? await acme.crypto.createPrivateEcdsaKey("P-256")
    : await acme.crypto.createPrivateKey(2048)
  const [, csr] = await acme.crypto.createCsr({ commonName: domains[0], altNames }, privateKey)

  const order = await client.createOrder({
    identifiers: domains.map((value) => ({ type: "dns", value })),
  })

  const authorizations = await client.getAuthorizations(order)
  const txtCleanups: Array<{ zoneId: string; recordId: string }> = []

  try {
    params.onStep?.("dns_challenge")
    for (const authz of authorizations) {
      const challenge = authz.challenges.find((c) => c.type === "dns-01")
      if (!challenge) throw new Error(`Нет DNS-01 challenge для ${authz.identifier.value}`)
      const txtValue = await client.getChallengeKeyAuthorization(challenge)
      const zoneId = await resolveZoneId(token, authz.identifier.value, settings.defaultZoneId)
      const recordName = `_acme-challenge.${authz.identifier.value}`
      const recordId = await createTxtRecord(token, zoneId, recordName, txtValue)
      txtCleanups.push({ zoneId, recordId })
    }

    await sleep(15_000)

    for (const authz of authorizations) {
      const challenge = authz.challenges.find((c) => c.type === "dns-01")
      if (!challenge) continue
      await client.verifyChallenge(authz, challenge)
      await client.completeChallenge(challenge)
      await client.waitForValidStatus(authz)
    }

    params.onStep?.("finalize")
    const finalized = await client.finalizeOrder(order, csr)
    const certPem = await client.getCertificate(finalized)

    params.onStep?.("import")
    const clientRos = MikrotikClient.fromServer(params.server)
    const safeBase = params.certName.replace(/[^a-zA-Z0-9._-]+/g, "_")
    const certFile = `${safeBase}.crt`
    const keyFile = `${safeBase}.key`
    const certRouterFile = await clientRos.uploadTextFile(certFile, certPem)
    const keyRouterFile = await clientRos.uploadTextFile(keyFile, privateKey.toString("utf8"))
    await clientRos.importCertificate({
      fileName: certRouterFile,
      name: params.certName,
      trusted: true,
      trustStore: params.trustStore.join(","),
    })
    await clientRos.importCertificate({
      fileName: keyRouterFile,
      name: params.certName,
      trusted: true,
      trustStore: params.trustStore.join(","),
    })
  } finally {
    params.onStep?.("cleanup")
    for (const item of txtCleanups) {
      try {
        await deleteTxtRecord(token, item.zoneId, item.recordId)
      } catch {
        /* ignore cleanup errors */
      }
    }
  }
}
