"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.performDirectSignup = performDirectSignup;
const axios_1 = __importDefault(require("axios"));
const crypto = __importStar(require("node:crypto"));
const zod_1 = require("zod");
const constants_js_1 = require("../lib/constants.js");
const logger_js_1 = require("../lib/observability/logger.js");
const log = (0, logger_js_1.createLogger)('direct-signup');
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_EXPIRES_IN_SECONDS = 86_400 * 365;
// Discriminated union response schemas from the provisioning endpoint.
// `dashboard_url` — optional magic-link URL (amplitude/javascript PR #108967).
const OAuthProvisioningSchema = zod_1.z.object({
    type: zod_1.z.literal('oauth'),
    oauth: zod_1.z.object({ code: zod_1.z.string().min(1) }),
    // `.nullish()` (no `min(1)`): a metadata field with strict validation
    // would fail-closed the entire signup whenever the API returns an empty
    // string or null. Treat empty as null at the read site.
    dashboard_url: zod_1.z.string().nullish(),
});
const RedirectSchema = zod_1.z.object({
    type: zod_1.z.literal('requires_auth'),
    requires_auth: zod_1.z.object({
        type: zod_1.z.literal('redirect'),
        redirect: zod_1.z.object({ url: zod_1.z.string() }),
    }),
});
const ErrorSchema = zod_1.z.object({
    type: zod_1.z.literal('error'),
    error: zod_1.z.object({ code: zod_1.z.string(), message: zod_1.z.string() }),
});
const TokenSchema = zod_1.z.object({
    access_token: zod_1.z.string(),
    id_token: zod_1.z.string(),
    refresh_token: zod_1.z.string(),
    token_type: zod_1.z.string(),
    expires_in: zod_1.z.number().int().positive().max(MAX_EXPIRES_IN_SECONDS),
});
const OAuthErrorBodySchema = zod_1.z.object({
    error: zod_1.z.string(),
    error_description: zod_1.z.string().optional(),
});
function provisioningUrl(zone) {
    // Dev/testing override — full URL (no /t/ prefix added). Unset in prod.
    const override = process.env.AMPLITUDE_WIZARD_SIGNUP_URL;
    if (override)
        return override;
    return `${constants_js_1.OUTBOUND_URLS.app[zone]}/t/agentic/signup/v1`;
}
/**
 * Attempts to create an Amplitude account and obtain tokens directly via the
 * provisioning endpoint (amplitude/javascript PR #103683). Callers should fall
 * back to the OAuth redirect flow on `requires_redirect` or `error`.
 */
async function performDirectSignup(input) {
    const { oAuthHost, oAuthClientId } = constants_js_1.AMPLITUDE_ZONE_SETTINGS[input.zone];
    const url = provisioningUrl(input.zone);
    // The server uses this as the OAuth `confirmationSecret` when issuing the
    // auth code. We send it for server-side correlation; there's no echo to
    // verify against (unlike browser OAuth `state`).
    const state = crypto.randomBytes(16).toString('hex');
    log.debug('[direct-signup] POST', { url, zone: input.zone });
    let response;
    try {
        response = await axios_1.default.post(url, {
            email: input.email,
            scopes: ['openid', 'offline'],
            state,
            client_id: oAuthClientId,
            redirect_uri: `http://localhost:${constants_js_1.OAUTH_PORT}/callback`,
            full_name: input.fullName,
        }, {
            headers: { 'Content-Type': 'application/json' },
            timeout: REQUEST_TIMEOUT_MS,
            validateStatus: (s) => s < 500,
        });
    }
    catch (e) {
        return {
            kind: 'error',
            message: e instanceof Error ? e.message : String(e),
        };
    }
    const parsedRedirect = RedirectSchema.safeParse(response.data);
    if (parsedRedirect.success)
        return { kind: 'requires_redirect' };
    const parsedError = ErrorSchema.safeParse(response.data);
    if (parsedError.success) {
        return {
            kind: 'error',
            message: parsedError.data.error.message,
            code: parsedError.data.error.code,
        };
    }
    const parsedCode = OAuthProvisioningSchema.safeParse(response.data);
    if (!parsedCode.success) {
        if (response.status === 429) {
            log.warn('[direct-signup] provisioning rate limited');
            return { kind: 'error', message: 'Provisioning rate limited (HTTP 429)' };
        }
        if (response.status >= 400) {
            log.warn('[direct-signup] provisioning client error', {
                status: response.status,
            });
            return {
                kind: 'error',
                message: `Provisioning failed with HTTP ${response.status}`,
            };
        }
        log.error('[direct-signup] unexpected response shape', {
            status: response.status,
        });
        return {
            kind: 'error',
            message: `Unexpected response (${response.status})`,
        };
    }
    // Exchange the auth code for tokens.
    let tokenResponse;
    try {
        tokenResponse = await axios_1.default.post(`${oAuthHost}/oauth2/token`, new URLSearchParams({
            grant_type: 'authorization_code',
            code: parsedCode.data.oauth.code,
            redirect_uri: `http://localhost:${constants_js_1.OAUTH_PORT}/callback`,
            client_id: oAuthClientId,
        }).toString(), {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            timeout: REQUEST_TIMEOUT_MS,
            validateStatus: (s) => s < 500,
        });
    }
    catch (e) {
        return {
            kind: 'error',
            message: `Token exchange failed: ${e instanceof Error ? e.message : String(e)}`,
        };
    }
    if (tokenResponse.status >= 400) {
        const parsedOAuthError = OAuthErrorBodySchema.safeParse(tokenResponse.data);
        if (parsedOAuthError.success) {
            const { error, error_description } = parsedOAuthError.data;
            const description = error_description ? `: ${error_description}` : '';
            log.warn('[direct-signup] token exchange error', { error });
            return {
                kind: 'error',
                message: `Token exchange ${tokenResponse.status}: ${error}${description}`,
            };
        }
        log.warn('[direct-signup] token exchange failed', {
            status: tokenResponse.status,
        });
        return {
            kind: 'error',
            message: `Token exchange failed (${tokenResponse.status})`,
        };
    }
    const parsedTokens = TokenSchema.safeParse(tokenResponse.data);
    if (!parsedTokens.success) {
        return {
            kind: 'error',
            message: 'Token exchange returned invalid response',
        };
    }
    // Source `expiresAt` from id_token's exp claim (id_token TTL is the
    // binding constraint for API calls). Falls back to `expires_in` and
    // then to a 1-hour default if either is unusable. See
    // `src/utils/jwt-exp.ts` for rationale.
    const { resolveStoredExpiryMs } = await import('./jwt-exp.js');
    const expiresAt = new Date(resolveStoredExpiryMs({
        idToken: parsedTokens.data.id_token,
        expiresInSeconds: parsedTokens.data.expires_in,
    })).toISOString();
    return {
        kind: 'success',
        tokens: {
            accessToken: parsedTokens.data.access_token,
            idToken: parsedTokens.data.id_token,
            refreshToken: parsedTokens.data.refresh_token,
            expiresAt,
            zone: input.zone,
        },
        // Coerce empty-string to null so downstream code (which displays the
        // URL or short-circuits on missing) doesn't have to handle "" as a
        // distinct third case.
        dashboardUrl: parsedCode.data.dashboard_url || null,
    };
}
