"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 HetznerObjectStorageProvisioner_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HetznerObjectStorageProvisioner = void 0;
const common_1 = require("@nestjs/common");
const object_storage_provisioner_interface_1 = require("../../../../storage/interfaces/object-storage-provisioner.interface");
const storage_backend_provider_enum_1 = require("../../../../storage/enums/storage-backend-provider.enum");
const generic_s3_backend_1 = require("../../../../storage/implementations/generic-s3.backend");
const hetzner_object_storage_connection_service_1 = require("./hetzner-object-storage-connection.service");
const HETZNER_DEFAULT_REGION = 'nbg1';
function endpointFor(region) {
    return `https://${region}.your-objectstorage.com`;
}
/**
 * Provisioner Hetzner Object Storage — SEMI_AUTO.
 * Hetzner Object Storage non espone API per gestire credenziali, quindi
 * l'utente deve incollarle una volta tramite il flusso "Connect Hetzner
 * Object Storage". Una volta collegate, il bucket viene creato automaticamente
 * via S3 API.
 */
let HetznerObjectStorageProvisioner = HetznerObjectStorageProvisioner_1 = class HetznerObjectStorageProvisioner {
    constructor(connectionService, genericS3) {
        this.connectionService = connectionService;
        this.genericS3 = genericS3;
        this.logger = new common_1.Logger(HetznerObjectStorageProvisioner_1.name);
        this.provider = storage_backend_provider_enum_1.StorageBackendProvider.HETZNER_OBJECT_STORAGE;
        this.capability = object_storage_provisioner_interface_1.ProvisionerCapability.SEMI_AUTO;
    }
    async isReady(_userId) {
        const creds = await this.connectionService.loadCreds();
        if (!creds) {
            return {
                ready: false,
                reason: 'CONNECT_HETZNER_OBJECT_STORAGE_REQUIRED',
                message: 'Per attivare i backup su Hetzner, collega le credenziali Hetzner Object Storage. Le trovi nella Hetzner Console → Project → Security → Object Storage Credentials.',
            };
        }
        return { ready: true };
    }
    async provisionDestination(input) {
        const creds = await this.connectionService.loadCreds();
        if (!creds) {
            throw new Error('Hetzner Object Storage credentials not configured. Call connect endpoint first.');
        }
        const region = input.desiredRegion ?? creds.region ?? HETZNER_DEFAULT_REGION;
        const endpoint = endpointFor(region);
        const bucket = input.desiredBucketName ?? this.defaultBucketName(input.userId);
        const exists = (await this.genericS3.testConnection({
            provider: this.provider,
            endpoint,
            region,
            bucket,
            accessKey: creds.accessKey,
            secretKey: creds.secretKey,
            forcePathStyle: true,
        })).healthy;
        if (!exists) {
            await this.genericS3.ensureBucket({
                provider: this.provider,
                endpoint,
                region,
                bucket,
                accessKey: creds.accessKey,
                secretKey: creds.secretKey,
                forcePathStyle: true,
            });
        }
        return {
            bucket,
            region,
            endpoint,
            forcePathStyle: true,
            pathPrefix: `flui/${input.clusterId}`,
            accessKey: creds.accessKey,
            secretKey: creds.secretKey,
            // Costi calcolati dal BillingEstimatorService (per-provider table) in cents-per-TB.
            usableForEtcdL1: true,
            alreadyExisted: exists,
        };
    }
    defaultBucketName(userId) {
        const short = userId.replaceAll('-', '').slice(0, 12).toLowerCase();
        return `flui-backups-${short}`;
    }
};
exports.HetznerObjectStorageProvisioner = HetznerObjectStorageProvisioner;
exports.HetznerObjectStorageProvisioner = HetznerObjectStorageProvisioner = HetznerObjectStorageProvisioner_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [hetzner_object_storage_connection_service_1.HetznerObjectStorageConnectionService,
        generic_s3_backend_1.GenericS3Backend])
], HetznerObjectStorageProvisioner);
