"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 HetznerVmBackupService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HetznerVmBackupService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const generated_1 = require("../../../../../modules/providers/implementations/hetzner/generated");
const cloud_provider_enum_1 = require("../../../enums/cloud-provider.enum");
let HetznerVmBackupService = HetznerVmBackupService_1 = class HetznerVmBackupService {
    constructor(configService, credentialProvider) {
        this.configService = configService;
        this.credentialProvider = credentialProvider;
        this.logger = new common_1.Logger(HetznerVmBackupService_1.name);
        this.basePath = this.configService.get('HETZNER_API_BASE_PATH', 'https://api.hetzner.cloud/v1');
    }
    getCapability() {
        return {
            supported: true,
            retentionDays: 7,
            scope: 'whole-vm-no-volumes',
            pricingModel: 'percent-of-server-monthly',
            pricingPercent: 20,
            notes: "Hetzner Cloud Backups: snapshot giornalieri automatici dell'intera VM (OS + disco primario), 7 slot rotanti. NON include i Volumes esterni. Costo: +20% del prezzo mensile del server.",
        };
    }
    async enableForServer(serverProviderId) {
        const id = this.parseServerId(serverProviderId);
        const api = await this.serverActionsApi();
        try {
            await api.enableServerBackup(id);
        }
        catch (err) {
            // 409 / "already enabled" → idempotent success
            const code = err?.response?.data?.error?.code;
            if (code === 'locked' || code === 'backup_already_enabled') {
                this.logger.warn(`Backup enable on server ${id} reported ${code} — treating as already enabled`);
                return;
            }
            throw err;
        }
    }
    async disableForServer(serverProviderId) {
        const id = this.parseServerId(serverProviderId);
        const api = await this.serverActionsApi();
        await api.disableServerBackup(id);
    }
    async getStatusForServer(serverProviderId) {
        const id = this.parseServerId(serverProviderId);
        const api = await this.serversApi();
        const res = await api.getServer(id);
        const server = res.data.server;
        return {
            serverProviderId,
            enabled: !!server.backup_window,
            backupWindow: server.backup_window ?? null,
        };
    }
    async listBackupsForServer(serverProviderId) {
        const id = this.parseServerId(serverProviderId);
        const api = await this.imagesApi();
        const res = await api.listImages(undefined, [generated_1.ListImagesTypeEnum.Backup], undefined, [String(id)]);
        const images = res.data.images ?? [];
        return images.map((img) => ({
            id: String(img.id),
            serverProviderId,
            name: img.name ?? null,
            description: img.description ?? null,
            createdAt: img.created,
            sizeGb: typeof img.image_size === 'number'
                ? img.image_size
                : typeof img.disk_size === 'number'
                    ? img.disk_size
                    : null,
            imageType: img.type,
        }));
    }
    parseServerId(serverProviderId) {
        const n = Number(serverProviderId);
        if (!Number.isFinite(n) || n <= 0) {
            throw new common_1.BadRequestException(`Invalid Hetzner server id: ${serverProviderId}`);
        }
        return n;
    }
    async configuration() {
        const token = await this.credentialProvider.getActiveApiToken(cloud_provider_enum_1.CloudProvider.HETZNER);
        return new generated_1.Configuration({
            accessToken: token,
            basePath: this.basePath,
        });
    }
    async serverActionsApi() {
        return new generated_1.ServerActionsApi(await this.configuration());
    }
    async serversApi() {
        return new generated_1.ServersApi(await this.configuration());
    }
    async imagesApi() {
        return new generated_1.ImagesApi(await this.configuration());
    }
};
exports.HetznerVmBackupService = HetznerVmBackupService;
exports.HetznerVmBackupService = HetznerVmBackupService = HetznerVmBackupService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(1, (0, common_1.Inject)('ICredentialProvider')),
    __metadata("design:paramtypes", [config_1.ConfigService, Object])
], HetznerVmBackupService);
