"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@oclif/core");
const chalk_1 = __importDefault(require("chalk"));
const config_storage_1 = require("../../lib/config-storage");
const profile_manager_1 = require("../../lib/profile-manager");
class AuthGenerateApiKey extends core_1.Command {
    async run() {
        const { flags } = await this.parse(AuthGenerateApiKey);
        const sessionToken = flags.token ?? process.env.FLUI_SESSION_TOKEN;
        if (!sessionToken) {
            this.error('A session Bearer token is required.\n' +
                'Pass it via --token <jwt> or set FLUI_SESSION_TOKEN.', { exit: 2 });
        }
        const profile = flags.profile ?? profile_manager_1.ProfileManager.getActiveProfile();
        const storage = new config_storage_1.ConfigStorage(profile);
        const baseUrl = storage.getApiUrlOrThrow();
        let expiresAt;
        if (flags.expires) {
            const d = new Date();
            d.setDate(d.getDate() + flags.expires);
            expiresAt = d.toISOString();
        }
        this.log(chalk_1.default.dim(`API URL: ${baseUrl}`));
        this.log(chalk_1.default.dim(`Profile: ${profile}`));
        let result;
        try {
            const res = await fetch(`${baseUrl}/auth/api-keys`, {
                method: 'POST',
                headers: {
                    Authorization: `Bearer ${sessionToken}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ name: flags.name, expiresAt }),
            });
            const body = (await res.json());
            if (!res.ok) {
                const msg = body.message ?? `HTTP ${res.status}`;
                this.error(`API error: ${msg}`, { exit: 1 });
            }
            result = body;
        }
        catch (e) {
            this.error(`Request failed: ${e.message}`, { exit: 1 });
        }
        storage.setApiKey(result.key);
        this.log('');
        this.log(chalk_1.default.green('✔ API key generated and saved to profile'));
        this.log(`  ${chalk_1.default.bold('Profile:')}  ${profile}`);
        this.log(`  ${chalk_1.default.bold('Key ID:')}   ${result.id}`);
        this.log(`  ${chalk_1.default.bold('Name:')}     ${result.name}`);
        if (result.expiresAt) {
            this.log(`  ${chalk_1.default.bold('Expires:')}  ${result.expiresAt}`);
        }
        this.log('');
        this.log(chalk_1.default.yellow('  ⚠  The plaintext key is not shown and cannot be retrieved again.'));
        this.log(chalk_1.default.dim('  It is stored encrypted in ~/.flui/profiles/' +
            profile +
            '/config.json'));
        this.log('');
        this.log(chalk_1.default.dim('Scripts will now pick it up automatically via ConfigStorage. ' +
            'You can also export it with: FLUI_API_KEY=$(flui config get apiKey)'));
    }
}
AuthGenerateApiKey.description = 'Generate a Flui M2M API key and save it to the active profile (OIDC mode only). ' +
    'Pass your Zitadel session token via --token or FLUI_SESSION_TOKEN.';
AuthGenerateApiKey.examples = [
    '<%= config.bin %> <%= command.id %> --token <zitadel-jwt>',
    '<%= config.bin %> <%= command.id %> --name ci-pipeline --expires 365',
    'FLUI_SESSION_TOKEN=<jwt> <%= config.bin %> <%= command.id %>',
];
AuthGenerateApiKey.flags = {
    token: core_1.Flags.string({
        description: 'Session Bearer token (or env FLUI_SESSION_TOKEN)',
    }),
    name: core_1.Flags.string({
        description: 'Human-readable name for the key',
        default: 'cli',
    }),
    expires: core_1.Flags.integer({
        description: 'Expiry in days from now (omit for no expiry)',
    }),
    profile: core_1.Flags.string({
        description: 'Profile to save the key into (default: active profile)',
    }),
};
exports.default = AuthGenerateApiKey;
