"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 api_client_1 = require("../../lib/api-client");
const config_storage_1 = require("../../lib/config-storage");
class IntegrationList extends core_1.Command {
    async run() {
        const configStorage = new config_storage_1.ConfigStorage();
        const apiUrl = configStorage.getApiUrlOrThrow();
        const apiKey = configStorage.getApiKey();
        if (!apiKey) {
            this.error('Not logged in. Run `flui auth login` first.', { exit: 1 });
        }
        const api = new api_client_1.ApiClient({ baseUrl: apiUrl, apiKey });
        let github;
        try {
            github = await api.get('/repositories/github/status');
        }
        catch (error) {
            this.error(`Could not fetch GitHub status: ${error.message}`, {
                exit: 1,
            });
        }
        let ghcrPat = null;
        try {
            ghcrPat = await api.get('/repositories/github-app/packages-pat/status');
        }
        catch {
            /* empty */
        }
        console.log('');
        console.log(`  ${chalk_1.default.bold('PROVIDER')}      ${chalk_1.default.bold('STATUS')}`);
        console.log(`  ${'─'.repeat(12)}  ${'─'.repeat(60)}`);
        console.log(`  github        ${this.renderGithubStatus(github)}`);
        console.log(`  ghcr-pat      ${this.renderGhcrPatStatus(ghcrPat)}`);
        console.log('');
    }
    renderGithubStatus(github) {
        if (!github.connected) {
            return `${chalk_1.default.yellow('not connected')} — run \`flui integration connect github\``;
        }
        const since = github.connectedAt
            ? new Date(github.connectedAt).toISOString().slice(0, 10)
            : 'unknown';
        return `${chalk_1.default.green('connected')} as ${chalk_1.default.bold(github.githubUsername ?? '?')} (since ${since})`;
    }
    renderGhcrPatStatus(ghcrPat) {
        if (!ghcrPat?.configured) {
            return `${chalk_1.default.yellow('not configured')} — required for deploys, run \`flui integration ghcr-pat set\``;
        }
        const days = ghcrPat.daysUntilExpiry;
        if (days == null)
            return chalk_1.default.green('valid');
        if (days < 0)
            return chalk_1.default.red(`expired ${-days}d ago`);
        if (days <= 14)
            return chalk_1.default.yellow(`expires in ${days}d`);
        return chalk_1.default.green(`valid (expires in ${days}d)`);
    }
}
IntegrationList.description = 'List third-party integrations configured for your account and show whether each is connected.';
IntegrationList.examples = ['<%= config.bin %> <%= command.id %>'];
exports.default = IntegrationList;
