"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const official_channels_store_1 = require("../../channels/official-channels-store");
const official_channels_runtime_1 = require("../../channels/official-channels-runtime");
const auth_middleware_1 = require("../middleware/auth-middleware");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const router = (0, express_1.Router)();
function buildChannelsStatus(config = (0, config_loader_facade_1.getOfficialChannelsConfig)()) {
    const environment = (0, official_channels_runtime_1.getOfficialChannelsEnvironmentStatus)();
    const channels = (0, official_channels_runtime_1.expandOfficialChannelSelection)('all').map((channelId) => {
        const tokenStatus = (0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId)
            ? (0, official_channels_store_1.getOfficialChannelTokenStatus)(channelId)
            : undefined;
        const selected = config.selected.includes(channelId);
        return {
            id: channelId,
            selected,
            displayName: (0, official_channels_runtime_1.getOfficialChannelDisplayName)(channelId),
            pluginSpec: (0, official_channels_runtime_1.getOfficialChannelPluginSpec)(channelId),
            summary: (0, official_channels_runtime_1.getOfficialChannelSummary)(channelId),
            requiresToken: (0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId),
            envKey: (0, official_channels_runtime_1.getOfficialChannelEnvKey)(channelId),
            tokenConfigured: (0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId) &&
                (0, official_channels_store_1.hasConfiguredOfficialChannelToken)(channelId),
            tokenAvailable: tokenStatus?.available ?? false,
            tokenSource: tokenStatus?.source,
            tokenPath: tokenStatus?.tokenPath,
            savedInClaudeState: tokenStatus?.savedInClaudeState ?? false,
            processEnvAvailable: tokenStatus?.processEnvAvailable ?? false,
            unavailableReason: (0, official_channels_runtime_1.getOfficialChannelUnavailableReason)(channelId),
            manualSetupCommands: (0, official_channels_runtime_1.getOfficialChannelManualSetupCommands)(channelId),
            setup: (0, official_channels_runtime_1.buildOfficialChannelSetupSummary)({
                id: channelId,
                displayName: (0, official_channels_runtime_1.getOfficialChannelDisplayName)(channelId),
                selected,
                requiresToken: (0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId),
                tokenAvailable: tokenStatus?.available ?? false,
                tokenSource: tokenStatus?.source,
                savedInClaudeState: tokenStatus?.savedInClaudeState ?? false,
                processEnvAvailable: tokenStatus?.processEnvAvailable ?? false,
                unavailableReason: (0, official_channels_runtime_1.getOfficialChannelUnavailableReason)(channelId),
            }),
        };
    });
    return {
        bunInstalled: environment.bunInstalled,
        supportedProfiles: environment.supportedProfiles,
        supportMessage: (0, official_channels_runtime_1.getOfficialChannelsSupportMessage)(),
        accountStatusCaveat: (0, official_channels_runtime_1.getOfficialChannelsAccountStatusCaveat)(),
        stateScopeMessage: environment.stateScopeMessage,
        claudeVersion: environment.claudeVersion,
        auth: environment.auth,
        summary: (0, official_channels_runtime_1.buildOfficialChannelsReadinessSummary)({
            config,
            environment,
            channels: channels.map((channel) => ({
                id: channel.id,
                displayName: channel.displayName,
                selected: channel.selected,
                requiresToken: channel.requiresToken,
                tokenAvailable: channel.tokenAvailable,
                tokenSource: channel.tokenSource,
                savedInClaudeState: channel.savedInClaudeState,
                processEnvAvailable: channel.processEnvAvailable,
                unavailableReason: channel.unavailableReason,
            })),
        }),
        launchPreview: (0, official_channels_runtime_1.buildOfficialChannelsLaunchPreview)({
            config,
            environment,
            channels: channels.map((channel) => ({
                id: channel.id,
                displayName: channel.displayName,
                selected: channel.selected,
                requiresToken: channel.requiresToken,
                tokenAvailable: channel.tokenAvailable,
                tokenSource: channel.tokenSource,
                savedInClaudeState: channel.savedInClaudeState,
                processEnvAvailable: channel.processEnvAvailable,
                unavailableReason: channel.unavailableReason,
            })),
        }),
        channels,
    };
}
router.use((req, res, next) => {
    if ((0, auth_middleware_1.requireLocalAccessWhenAuthDisabled)(req, res, 'Official Channels settings require localhost access when dashboard auth is disabled.')) {
        next();
    }
});
router.get('/', (_req, res) => {
    const config = (0, config_loader_facade_1.getOfficialChannelsConfig)();
    res.json({
        config,
        status: buildChannelsStatus(config),
    });
});
router.put('/', (req, res) => {
    const { selected, unattended } = req.body;
    if (selected !== undefined &&
        (!Array.isArray(selected) ||
            selected.some((value) => typeof value !== 'string' || !(0, official_channels_runtime_1.isOfficialChannelId)(value)))) {
        res.status(400).json({ error: 'selected must be an array of official channel IDs' });
        return;
    }
    if (unattended !== undefined && typeof unattended !== 'boolean') {
        res.status(400).json({ error: 'unattended must be a boolean' });
        return;
    }
    try {
        const updated = (0, config_loader_facade_1.mutateConfig)((config) => {
            config.channels = {
                selected: selected !== undefined ? [...new Set(selected)] : (config.channels?.selected ?? []),
                unattended: unattended ?? config.channels?.unattended ?? false,
            };
        });
        res.json({ success: true, config: updated.channels });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
router.put('/:channelId/token', (req, res) => {
    const { channelId } = req.params;
    const { token } = req.body;
    if (!(0, official_channels_runtime_1.isOfficialChannelId)(channelId) || !(0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId)) {
        res.status(400).json({ error: 'channelId must be a token-based official channel' });
        return;
    }
    if (typeof token !== 'string') {
        res.status(400).json({ error: 'token must be a string' });
        return;
    }
    try {
        const tokenPath = (0, official_channels_store_1.setConfiguredOfficialChannelToken)(channelId, token);
        res.json({ success: true, tokenConfigured: true, tokenPath });
    }
    catch (error) {
        const message = error.message;
        const statusCode = message.includes('cannot be empty') || message.includes('cannot exceed') ? 400 : 500;
        res.status(statusCode).json({ error: message });
    }
});
router.delete('/:channelId/token', (req, res) => {
    const { channelId } = req.params;
    if (!(0, official_channels_runtime_1.isOfficialChannelId)(channelId) || !(0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId)) {
        res.status(400).json({ error: 'channelId must be a token-based official channel' });
        return;
    }
    try {
        const clearedPaths = (0, official_channels_store_1.clearConfiguredOfficialChannelTokensEverywhere)(channelId);
        res.json({
            success: true,
            tokenConfigured: false,
            clearedPaths,
        });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
exports.default = router;
//# sourceMappingURL=channels-routes.js.map