"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loginCommand = void 0;
const helpers_1 = require("./helpers");
exports.loginCommand = {
    command: 'login',
    describe: 'Log in to your Amplitude account',
    builder: (yargs) => yargs.options({
        region: {
            describe: 'data center region (us or eu)',
            choices: ['us', 'eu'],
            default: 'us',
            type: 'string',
            // `--zone` is the pre-existing name; kept as an alias so any
            // scripts using `wizard login --zone` continue to work.
            alias: 'zone',
        },
    }),
    handler: (argv) => {
        void (async () => {
            (0, helpers_1.setUI)(new helpers_1.LoggingUI());
            const { performAmplitudeAuth } = await import('../utils/oauth.js');
            const { fetchAmplitudeUser } = await import('../lib/api.js');
            const { storeToken } = await import('../utils/ampli-settings.js');
            // `--region` is canonical; `argv.zone` is the yargs alias mirror.
            const zone = argv.region;
            try {
                const { getStoredUser, getStoredToken } = await import('../utils/ampli-settings.js');
                // If a valid cached session exists, display the stored user without
                // re-fetching from the API (the cached idToken may be expired).
                const cachedToken = getStoredToken(undefined, zone);
                const cachedUser = cachedToken ? getStoredUser() : undefined;
                if (cachedUser && cachedUser.id !== 'pending') {
                    (0, helpers_1.getUI)().log.success(`Already logged in as ${cachedUser.firstName} ${cachedUser.lastName} <${cachedUser.email}>`);
                    if (cachedUser.zone !== 'us') {
                        (0, helpers_1.getUI)().note(`Zone: ${cachedUser.zone}`);
                    }
                    process.exit(0);
                }
                const auth = await performAmplitudeAuth({ zone });
                const user = await fetchAmplitudeUser(auth.idToken, auth.zone);
                // Source `expiresAt` from the id_token's actual `exp` claim.
                // The wizard authenticates with the id_token (not the access
                // token) for every API call, so the stored field needs to
                // reflect the id_token's TTL — otherwise tryRefreshToken's
                // proactive trigger can be off by hours and id-token-401s
                // surface as misleading auth_required errors. Falls back
                // gracefully if the JWT is somehow undecodable. See
                // `src/utils/jwt-exp.ts` for the architecture rationale.
                const { resolveStoredExpiryMs } = await import('../utils/jwt-exp.js');
                const expiresAt = new Date(resolveStoredExpiryMs({ idToken: auth.idToken })).toISOString();
                storeToken({
                    id: user.id,
                    firstName: user.firstName,
                    lastName: user.lastName,
                    email: user.email,
                    zone: auth.zone,
                }, {
                    accessToken: auth.accessToken,
                    idToken: auth.idToken,
                    refreshToken: auth.refreshToken,
                    expiresAt,
                });
                (0, helpers_1.getUI)().log.success(`Logged in as ${user.firstName} ${user.lastName} <${user.email}>`);
                if (user.orgs.length > 0) {
                    (0, helpers_1.getUI)().note(`Org: ${user.orgs.map((o) => o.name).join(', ')}`);
                }
                process.exit(0);
            }
            catch (e) {
                (0, helpers_1.getUI)().log.error(`Login failed: ${e instanceof Error ? e.message : String(e)}`);
                process.exit(1);
            }
        })();
    },
};
