"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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var ClusterDnsCleanupService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClusterDnsCleanupService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const dns_zone_entity_1 = require("../entities/dns-zone.entity");
const dns_provider_factory_1 = require("../../providers/services/dns-provider.factory");
let ClusterDnsCleanupService = ClusterDnsCleanupService_1 = class ClusterDnsCleanupService {
    constructor(dnsZoneRepository, dnsProviderFactory) {
        this.dnsZoneRepository = dnsZoneRepository;
        this.dnsProviderFactory = dnsProviderFactory;
        this.logger = new common_1.Logger(ClusterDnsCleanupService_1.name);
    }
    async deleteRecordsByClusterId(clusterId) {
        const zones = await this.dnsZoneRepository.find();
        let deleted = 0;
        for (const zone of zones) {
            deleted += await this.deleteRecordsInZone(zone, clusterId);
        }
        if (deleted > 0) {
            this.logger.log(`Removed ${deleted} DNS record(s) tagged with flui-cluster-id=${clusterId}`);
        }
        return deleted;
    }
    async deleteRecordsInZone(zone, clusterId) {
        const provider = this.dnsProviderFactory.getDnsProvider(zone.dnsProvider);
        if (!provider)
            return 0;
        let records;
        try {
            records = await provider.listRecords(zone.providerZoneId);
        }
        catch (err) {
            this.logger.warn(`Failed to list DNS records on zone ${zone.zoneName}: ${this.errMessage(err)}`);
            return 0;
        }
        const matching = records.filter((r) => {
            const labels = r.labels ?? {};
            return (labels['flui-cluster-id'] === clusterId &&
                labels['managed-by'] === 'flui-cloud');
        });
        let deleted = 0;
        for (const record of matching) {
            try {
                await provider.deleteRecord(zone.providerZoneId, record.recordId);
                deleted++;
                this.logger.log(`Deleted DNS record ${record.type} ${record.name} -> ${record.value} from zone ${zone.zoneName} (cluster ${clusterId})`);
            }
            catch (err) {
                this.logger.warn(`Failed to delete DNS record ${record.recordId} from zone ${zone.zoneName}: ${this.errMessage(err)}`);
            }
        }
        return deleted;
    }
    errMessage(err) {
        return err instanceof Error ? err.message : String(err);
    }
};
exports.ClusterDnsCleanupService = ClusterDnsCleanupService;
exports.ClusterDnsCleanupService = ClusterDnsCleanupService = ClusterDnsCleanupService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(dns_zone_entity_1.DnsZoneEntity)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        dns_provider_factory_1.DnsProviderFactory])
], ClusterDnsCleanupService);
