"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 ScalewayIamAdapter_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScalewayIamAdapter = void 0;
const common_1 = require("@nestjs/common");
const iam_1 = require("./generated/iam");
const cloud_provider_enum_1 = require("../../enums/cloud-provider.enum");
let ScalewayIamAdapter = ScalewayIamAdapter_1 = class ScalewayIamAdapter {
    constructor(credentialProvider) {
        this.credentialProvider = credentialProvider;
        this.iamBaseUrl = 'https://api.scaleway.com';
        this.logger = new common_1.Logger(ScalewayIamAdapter_1.name);
        this.cachedOrganizationId = null;
        this.cachedProjectId = null;
    }
    async createConfiguration() {
        const token = await this.credentialProvider.getActiveApiToken(cloud_provider_enum_1.CloudProvider.SCALEWAY);
        return new iam_1.Configuration({
            basePath: this.iamBaseUrl,
            apiKey: token,
        });
    }
    async createSSHKeysApi() {
        return new iam_1.SSHKeysApi(await this.createConfiguration());
    }
    /**
     * Returns the organization ID for the configured Scaleway API key.
     * Uses getAPIKey(accessKey) which requires no additional parameters.
     * The generated TypeScript types don't include organization_id but the real API returns it.
     * Result is cached for the lifetime of the adapter instance.
     */
    async getOrganizationId() {
        if (this.cachedOrganizationId)
            return this.cachedOrganizationId;
        const pair = await this.credentialProvider.getActiveAccessKeyPair(cloud_provider_enum_1.CloudProvider.SCALEWAY);
        const config = await this.createConfiguration();
        const apiKeysApi = new iam_1.APIKeysApi(config);
        const resp = await apiKeysApi.getAPIKey(pair.accessKey);
        const organizationId = resp.data?.organization_id;
        if (!organizationId) {
            throw new Error('Could not determine Scaleway organization ID — check API key permissions');
        }
        this.logger.debug(`Resolved organization ID: ${organizationId}`);
        this.cachedOrganizationId = organizationId;
        return organizationId;
    }
    /**
     * Returns the default project ID for the configured Scaleway API key.
     * Uses getAPIKey(accessKey) which requires no additional parameters.
     * Used for server and security group creation (requires project_id, not organization_id).
     */
    async getDefaultProjectId() {
        if (this.cachedProjectId)
            return this.cachedProjectId;
        const pair = await this.credentialProvider.getActiveAccessKeyPair(cloud_provider_enum_1.CloudProvider.SCALEWAY);
        const config = await this.createConfiguration();
        const apiKeysApi = new iam_1.APIKeysApi(config);
        const resp = await apiKeysApi.getAPIKey(pair.accessKey);
        const projectId = resp.data?.default_project_id;
        if (!projectId) {
            throw new Error('Could not determine Scaleway default project ID — check that the API key has a default project set');
        }
        this.cachedProjectId = projectId;
        return projectId;
    }
    async listSSHKeys() {
        const api = await this.createSSHKeysApi();
        const resp = await api.listSSHKeys();
        return resp.data.ssh_keys ?? [];
    }
    async createSSHKey(name, publicKey, _labels) {
        const api = await this.createSSHKeysApi();
        const projectId = await this.getDefaultProjectId();
        const resp = await api.createSSHKey({
            name,
            public_key: publicKey,
            project_id: projectId,
        });
        return { id: resp.data.id ?? '', fingerprint: resp.data.fingerprint };
    }
    async deleteSSHKey(id) {
        const api = await this.createSSHKeysApi();
        await api.deleteSSHKey(id);
    }
    async getSSHKey(id) {
        const api = await this.createSSHKeysApi();
        const resp = await api.getSSHKey(id);
        return resp.data;
    }
};
exports.ScalewayIamAdapter = ScalewayIamAdapter;
exports.ScalewayIamAdapter = ScalewayIamAdapter = ScalewayIamAdapter_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)('ICredentialProvider')),
    __metadata("design:paramtypes", [Object])
], ScalewayIamAdapter);
