import { Command, flags } from '@heroku-cli/command';
import * as color from '@heroku/heroku-cli-util/color';
import { HTTPError } from '@heroku/http-call';
import { Args, ux } from '@oclif/core';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import open from 'open';
import { attachmentResolver, resolveAddon } from '../../lib/addons/resolve.js';
export default class Open extends Command {
    static args = {
        addon: Args.string({ description: 'unique identifier or globally unique name of the add-on', required: true }),
    };
    static description = 'open an add-on\'s dashboard in your browser';
    static flags = {
        app: flags.app(),
        remote: flags.remote(),
        'show-url': flags.boolean({ description: 'show URL, do not open browser' }),
    };
    static topic = 'addons';
    static urlOpener = open;
    static async openUrl(url) {
        ux.stdout(`Opening ${color.info(url)}...`);
        await Open.urlOpener(url);
    }
    async run() {
        const { args: { addon }, flags } = await this.parse(Open);
        const { app } = flags;
        if (process.env.HEROKU_SUDO) {
            return this.sudo(app, addon);
        }
        let attachment = null;
        try {
            attachment = await attachmentResolver(this.heroku, app, addon);
        }
        catch (error) {
            if (error instanceof HTTPError && error.statusCode !== 404) {
                throw error;
            }
        }
        let webUrl;
        if (attachment) {
            webUrl = attachment.web_url;
        }
        else {
            const resolvedAddon = await resolveAddon(this.heroku, app, addon);
            webUrl = resolvedAddon.web_url;
        }
        if (flags['show-url']) {
            ux.stdout(webUrl);
        }
        else {
            await Open.openUrl(webUrl);
        }
    }
    async sudo(app, addon) {
        const sso = await this.heroku.request(`/apps/${app}/addons/${addon}/sso`, {
            headers: {
                Accept: 'application/vnd.heroku+json; version=3.sdk',
            },
            method: 'GET',
        });
        const { action, method } = sso.body;
        if (method === 'get') {
            await Open.openUrl(action);
        }
        else {
            const ssoPath = await this.writeSudoTemplate(app, addon, sso.body);
            await Open.openUrl(`file://${ssoPath}`);
        }
    }
    async writeSudoTemplate(app, addon, sso) {
        const ssoPath = path.join(os.tmpdir(), 'heroku-sso.html');
        const html = `<!DOCTYPE HTML>\n<html lang="en">\n  <head>\n    <meta charset="utf-8">\n    <title>Heroku Add-ons SSO</title>\n    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>\n  </head>\n\n  <body>\n    <h3>Opening ${addon}${app ? ` on ${app}` : ''}...</h3>\n    <form method="POST" action="${sso.action}">\n    </form>\n\n    <script>\n      var params = ${JSON.stringify(sso.params)}\n      var form = document.forms[0]\n      $(document).ready(function() {\n        $.each(params, function(key, value) {\n          $('<input>').attr({ type: 'hidden', name: key, value: value })\n            .appendTo(form)\n        })\n        form.submit()\n      })\n    </script>\n  </body>\n</html>`;
        await fs.writeFile(ssoPath, html);
        return ssoPath;
    }
}
