"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApiRouter = void 0;
const express_1 = require("express");
const common_stuff_1 = require("common-stuff");
const express_openapi_validator_1 = require("express-openapi-validator");
const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
const auth_1 = require("./auth");
const browse_1 = require("./browse");
const stream_1 = require("./stream");
const torrents_1 = require("./torrents");
const usage_1 = require("./usage");
const errors_1 = require("../helpers/errors");
const openapi_1 = require("../helpers/openapi");
function getApiRouter(globals, client) {
    const { config, logger } = globals;
    const app = express_1.Router();
    const apiKey = config.security.apiKey || config.security.streamApi.key;
    if (config.environment === 'development') {
        app.use('/api-docs', swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup(openapi_1.openapi));
    }
    app.get('/status', (_req, res) => res.send({ status: 'ok' }));
    if (config.security.apiEnabled) {
        app.use(express_openapi_validator_1.middleware({
            apiSpec: openapi_1.openapi,
            validateRequests: true,
            validateResponses: config.environment === 'development',
            ignorePaths: (path) => {
                return !['/api', '/stream', '/playlist'].some((v) => path.startsWith(v));
            },
            validateSecurity: apiKey
                ? {
                    handlers: {
                        apiKey: (req) => {
                            const [type = '', token] = (req.headers.authorization || '').split(' ');
                            return type.toLowerCase() === 'bearer' && token === apiKey;
                        },
                    },
                }
                : false,
        }));
        app.use(openapi_1.createRouter([
            ...auth_1.getAuthRouter(globals),
            ...browse_1.getBrowseRouter(globals),
            ...usage_1.getUsageRouter(globals),
            ...torrents_1.getTorrentsRouter(globals, client),
            ...stream_1.getStreamRouter(globals, client),
        ]));
        app.use('/api/?*', () => {
            throw new common_stuff_1.HttpError(common_stuff_1.HttpStatusCodes.NOT_FOUND);
        });
    }
    else {
        logger.info('API is disabled according to the config');
    }
    app.use(errors_1.handleApiErrors(logger));
    return app;
}
exports.getApiRouter = getApiRouter;
