"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AcmeCertificateService = void 0;
const common_1 = require("@nestjs/common");
const node_fs_1 = require("node:fs");
const certificate_provider_enum_1 = require("../enums/certificate-provider.enum");
const dns_provider_enum_1 = require("../enums/dns-provider.enum");
const project_root_util_1 = require("../../../common/utils/project-root.util");
const ACME_SERVERS = {
    [certificate_provider_enum_1.CertificateProvider.LETS_ENCRYPT]: 'https://acme-v02.api.letsencrypt.org/directory',
    [certificate_provider_enum_1.CertificateProvider.LETS_ENCRYPT_STAGING]: 'https://acme-staging-v02.api.letsencrypt.org/directory',
};
const DNS01_WEBHOOK_CONFIGS = {
    [dns_provider_enum_1.DnsProvider.HETZNER]: {
        groupName: 'acme.hetzner.com',
        solverName: 'hetzner',
        secretName: 'hetzner-secret',
        secretKey: 'token',
    },
};
let AcmeCertificateService = class AcmeCertificateService {
    generateClusterIssuerManifest(config) {
        const issuerName = this.getIssuerName(config.server);
        const template = (0, node_fs_1.readFileSync)((0, project_root_util_1.getProjectPath)('src', 'modules', 'dns', 'templates', 'cluster-issuer.yaml'), 'utf-8');
        return template
            .replaceAll('{{ISSUER_NAME}}', issuerName)
            .replaceAll('{{ACME_SERVER}}', config.server)
            .replaceAll('{{ACME_EMAIL}}', config.email)
            .replaceAll('{{PRIVATE_KEY_SECRET_REF}}', config.privateKeySecretRef);
    }
    generateCertificateManifest(config) {
        const template = (0, node_fs_1.readFileSync)((0, project_root_util_1.getProjectPath)('src', 'modules', 'dns', 'templates', 'certificate.yaml'), 'utf-8');
        const dnsNamesYaml = config.domains
            .map((d, i) => (i === 0 ? `- ${d}` : `    - ${d}`))
            .join('\n');
        return template
            .replaceAll('{{CERT_NAME}}', config.name)
            .replaceAll('{{NAMESPACE}}', config.namespace)
            .replaceAll('{{SECRET_NAME}}', config.secretName)
            .replaceAll('{{ISSUER_NAME}}', config.issuerName)
            .replaceAll('{{DNS_NAMES}}', dnsNamesYaml);
    }
    validateConfiguration(config) {
        const errors = [];
        if (!config.email?.includes('@')) {
            errors.push('A valid email address is required for ACME registration');
        }
        if (!config.server) {
            errors.push('ACME server URL is required');
        }
        if (!config.privateKeySecretRef) {
            errors.push('Private key secret reference is required');
        }
        return {
            valid: errors.length === 0,
            errors,
        };
    }
    getAcmeServerUrl(provider) {
        return (ACME_SERVERS[provider] ?? ACME_SERVERS[certificate_provider_enum_1.CertificateProvider.LETS_ENCRYPT]);
    }
    getIssuerName(server) {
        if (server.includes('staging')) {
            return 'letsencrypt-staging';
        }
        return 'letsencrypt-production';
    }
    getWildcardIssuerName(server) {
        return `${this.getIssuerName(server)}-wildcard`;
    }
    generateCombinedClusterIssuerManifest(config) {
        const issuerName = this.getWildcardIssuerName(config.server);
        const webhookConfig = this.getDns01WebhookConfig(config.dnsProvider);
        const template = (0, node_fs_1.readFileSync)((0, project_root_util_1.getProjectPath)('src', 'modules', 'dns', 'templates', 'cluster-issuer-combined.yaml'), 'utf-8');
        return template
            .replaceAll('{{ISSUER_NAME}}', issuerName)
            .replaceAll('{{ACME_SERVER}}', config.server)
            .replaceAll('{{ACME_EMAIL}}', config.email)
            .replaceAll('{{PRIVATE_KEY_SECRET_REF}}', `${issuerName}-key`)
            .replaceAll('{{ZONE_NAME}}', config.zoneName)
            .replaceAll('{{WEBHOOK_GROUP_NAME}}', webhookConfig.groupName)
            .replaceAll('{{WEBHOOK_SOLVER_NAME}}', webhookConfig.solverName)
            .replaceAll('{{WEBHOOK_SECRET_NAME}}', webhookConfig.secretName)
            .replaceAll('{{WEBHOOK_SECRET_KEY}}', webhookConfig.secretKey);
    }
    generateDns01ClusterIssuerManifest(config) {
        const issuerName = this.getIssuerName(config.server);
        const webhookConfig = this.getDns01WebhookConfig(config.dnsProvider);
        const template = (0, node_fs_1.readFileSync)((0, project_root_util_1.getProjectPath)('src', 'modules', 'dns', 'templates', 'cluster-issuer-dns01.yaml'), 'utf-8');
        return template
            .replaceAll('{{ISSUER_NAME}}', issuerName)
            .replaceAll('{{ACME_SERVER}}', config.server)
            .replaceAll('{{ACME_EMAIL}}', config.email)
            .replaceAll('{{PRIVATE_KEY_SECRET_REF}}', config.privateKeySecretRef)
            .replaceAll('{{ZONE_NAME}}', config.zoneName)
            .replaceAll('{{WEBHOOK_GROUP_NAME}}', webhookConfig.groupName)
            .replaceAll('{{WEBHOOK_SOLVER_NAME}}', webhookConfig.solverName)
            .replaceAll('{{WEBHOOK_SECRET_NAME}}', webhookConfig.secretName)
            .replaceAll('{{WEBHOOK_SECRET_KEY}}', webhookConfig.secretKey);
    }
    generateWildcardCertificateManifest(config) {
        const template = (0, node_fs_1.readFileSync)((0, project_root_util_1.getProjectPath)('src', 'modules', 'dns', 'templates', 'wildcard-certificate.yaml'), 'utf-8');
        return template
            .replaceAll('{{CERT_NAME}}', config.name)
            .replaceAll('{{NAMESPACE}}', config.namespace)
            .replaceAll('{{SECRET_NAME}}', config.secretName)
            .replaceAll('{{ISSUER_NAME}}', config.issuerName)
            .replaceAll('{{ZONE_NAME}}', config.zoneName);
    }
    generateDnsTokenSecretManifest(token, dnsProvider) {
        const webhookConfig = this.getDns01WebhookConfig(dnsProvider);
        const secret = {
            apiVersion: 'v1',
            kind: 'Secret',
            metadata: {
                name: webhookConfig.secretName,
                namespace: 'cert-manager',
                labels: { 'managed-by': 'flui-cloud' },
            },
            stringData: {
                [webhookConfig.secretKey]: token,
            },
        };
        return JSON.stringify(secret);
    }
    getDns01WebhookConfig(dnsProvider) {
        const config = DNS01_WEBHOOK_CONFIGS[dnsProvider];
        if (!config) {
            throw new Error(`DNS-01 webhook is not supported for provider "${dnsProvider}". ` +
                `Supported providers: ${Object.keys(DNS01_WEBHOOK_CONFIGS).join(', ')}`);
        }
        return config;
    }
};
exports.AcmeCertificateService = AcmeCertificateService;
exports.AcmeCertificateService = AcmeCertificateService = __decorate([
    (0, common_1.Injectable)()
], AcmeCertificateService);
