"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exchangeSSO = exchangeSSO;
const sso_1 = require("../modules/sso");
const sso_provision_1 = require("../services/user/sso-provision");
const auth_1 = require("../modules/auth");
/**
 * Exchange host authentication for a Long Tail JWT.
 *
 * Calls `sso.resolve(req)` to extract the host identity, JIT provisions
 * the user in `lt_users`, and returns a signed JWT the dashboard can
 * store for subsequent API calls.
 *
 * No request body required — the host's cookies/headers carry the auth.
 */
async function exchangeSSO(req) {
    try {
        const ssoConfig = (0, sso_1.getSSOConfig)();
        if (!ssoConfig) {
            return { status: 404, error: 'SSO not configured' };
        }
        const identity = await ssoConfig.resolve(req);
        if (!identity) {
            return { status: 401, error: 'Host authentication required' };
        }
        const provisioned = await (0, sso_provision_1.ssoProvision)(identity, ssoConfig);
        const highestType = provisioned.roles.some((r) => r.type === 'superadmin')
            ? 'superadmin'
            : provisioned.roles.some((r) => r.type === 'admin')
                ? 'admin'
                : 'member';
        const token = (0, auth_1.signToken)({
            userId: provisioned.userId,
            role: highestType,
            roles: provisioned.roles,
            sso: true,
        }, '24h');
        return {
            status: 200,
            data: {
                token,
                user: {
                    id: provisioned.userId,
                    external_id: identity.externalId,
                    display_name: identity.displayName || identity.externalId,
                    roles: provisioned.roles,
                },
            },
        };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
