"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.whoami = whoami;
const types_1 = require("@playdrop/types");
const config_1 = require("../config");
const commandContext_1 = require("../commandContext");
const http_1 = require("../http");
const messages_1 = require("../messages");
async function whoami(options = {}) {
    const ctx = await (0, commandContext_1.resolveAuthenticatedEnvironmentContext)('auth whoami', 'Checking your Playdrop account status', {
        env: options.env,
        workspacePath: process.cwd(),
    });
    if (!ctx) {
        return;
    }
    const resolvedCtx = ctx;
    const globalCurrentAccount = (0, config_1.getCurrentAccountSession)((0, config_1.loadConfig)());
    const hadStoredCurrentAccount = Boolean(globalCurrentAccount);
    async function doMe() {
        try {
            return await resolvedCtx.client.me();
        }
        catch (unknownError) {
            if (unknownError instanceof types_1.UnsupportedClientError) {
                (0, http_1.handleUnsupportedError)(unknownError, 'Whoami');
            }
            if (unknownError instanceof types_1.ApiError) {
                (0, messages_1.printErrorWithHelp)(`Request failed with status ${unknownError.status}.`, [
                    'Run "playdrop auth login" to refresh your credentials.',
                    'Use "playdrop auth whoami" again after logging in to confirm your status.',
                ], { command: 'whoami' });
                process.exitCode = 1;
                return null;
            }
            throw unknownError;
        }
    }
    let data = null;
    try {
        data = await doMe();
    }
    catch (e) {
        if (e instanceof http_1.CLIUnsupportedClientError) {
            return;
        }
        (0, messages_1.printNetworkIssue)('Could not reach the Playdrop API to check your account.', 'whoami');
        process.exitCode = 1;
        return;
    }
    if (!data)
        return;
    const username = data.user?.username?.trim();
    if (!username) {
        (0, messages_1.printErrorWithHelp)('The Playdrop API returned an unexpected response.', [
            'Retry "playdrop auth whoami" in a moment.',
            'If the problem continues, contact the Playdrop team.',
        ], { command: 'whoami' });
        process.exitCode = 1;
        return;
    }
    if (!hadStoredCurrentAccount) {
        (0, config_1.migrateLegacySession)({
            username,
            env: resolvedCtx.env,
            token: resolvedCtx.token,
        });
    }
    if (resolvedCtx.workspaceAuth) {
        console.log(`Workspace account: ${username} (${resolvedCtx.env})`);
        const resolutionSources = ['.playdrop.json'];
        if (options.env) {
            resolutionSources.push(`--env ${options.env}`);
        }
        console.log(`Resolved from: ${resolutionSources.join(' + ')}`);
        if (globalCurrentAccount
            && (globalCurrentAccount.username !== username || globalCurrentAccount.env !== resolvedCtx.env)) {
            console.log(`Global default: ${globalCurrentAccount.username} (${globalCurrentAccount.env})`);
        }
    }
    else {
        console.log(`${username} (${resolvedCtx.env})`);
        if (options.env) {
            console.log(`Resolved from: --env ${options.env}`);
        }
    }
    console.log('Next: run "playdrop getting-started" to see the recommended workflow.');
}
