"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.play = play;
const types_1 = require("@playdrop/types");
const commandContext_1 = require("../commandContext");
const appUrls_1 = require("../appUrls");
const browser_1 = require("../browser");
const http_1 = require("../http");
const messages_1 = require("../messages");
const output_1 = require("../output");
const refs_1 = require("../refs");
const devShared_1 = require("./devShared");
function printPlayRefValidationError(rawRef) {
    (0, messages_1.printErrorWithHelp)('A canonical app ref is required.', [
        'Use the format <creator>/app/<name>.',
        'Example: playdrop play playdrop/app/hangingout',
    ], { command: 'play' });
    process.exitCode = 1;
}
async function play(rawRef, options = {}) {
    let ref;
    try {
        ref = (0, refs_1.parseContentRef)(rawRef ?? '');
    }
    catch {
        printPlayRefValidationError(rawRef);
        return;
    }
    if (ref.kind !== 'app') {
        (0, messages_1.printErrorWithHelp)('The play command only supports app refs.', [
            'Use the format <creator>/app/<name>.',
            'Assets and asset packs do not have authenticated play routes.',
        ], { command: 'play' });
        process.exitCode = 1;
        return;
    }
    await (0, commandContext_1.withEnvironment)('play', 'Launching a published app', async ({ client, envConfig }) => {
        try {
            const response = await client.fetchAppBySlug(ref.creator, ref.name);
            const playUrl = (0, appUrls_1.buildPlatformPlayUrl)(envConfig.webBase, {
                creatorUsername: response.app.creatorUsername,
                appName: response.app.name,
                appType: response.app.type,
            });
            const playPath = new URL(playUrl).pathname;
            const launch = await client.startCliWebLaunch({
                redirectPath: playPath,
            });
            const payload = {
                ref: ref.ref,
                playUrl,
                launchUrl: launch.launchUrl,
                expiresAt: launch.expiresAt,
            };
            if (options.json) {
                (0, output_1.printJson)(payload);
                return;
            }
            console.log(`Play URL: ${playUrl}`);
            console.log(`Launch URL: ${launch.launchUrl}`);
            const opened = await (0, browser_1.openBrowserUrl)(launch.launchUrl).catch(() => false);
            if (opened) {
                console.log('Opened the app in your browser.');
            }
            else {
                console.log('Open the launch URL above in your browser.');
            }
        }
        catch (error) {
            if (error instanceof http_1.CLIUnsupportedClientError) {
                return;
            }
            if (error instanceof types_1.UnsupportedClientError) {
                (0, http_1.handleUnsupportedError)(error, 'Play');
                process.exitCode = 1;
                return;
            }
            if (error instanceof types_1.ApiError) {
                if (error.status === 404) {
                    (0, messages_1.printErrorWithHelp)(`No app was found for "${ref.ref}".`, [
                        'Check the ref and retry.',
                        'Run "playdrop browse --kind app" to discover public apps.',
                    ], { command: 'play' });
                    process.exitCode = 1;
                    return;
                }
                (0, messages_1.printErrorWithHelp)(`Could not launch "${ref.ref}" (status ${error.status}).`, [
                    'Run "playdrop auth whoami" to confirm your session.',
                    'Retry in a moment if the platform was just updated.',
                ], { command: 'play' });
                process.exitCode = 1;
                return;
            }
            if ((0, devShared_1.isNetworkError)(error)) {
                (0, messages_1.printNetworkIssue)('Could not reach the Playdrop API to launch the app.', 'play');
                process.exitCode = 1;
                return;
            }
            throw error;
        }
    });
}
