/*
 * Copyright (c) 2022.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import {generateDocumentation, Config} from "typescript-swagger";
import {getRootDirPath, getWritableDirPath} from "../paths";
import path from "path";
import env from "../../env";

const packageJson = require('../../../package.json');
const tsConfig = require('../../../tsconfig.json');

const url = new URL(env.apiUrl);
let host : string = (url.host + url.pathname).replace(/([^:]\/)\/+/g, "$1");
host = host.substr(-1, 1) === '/' ? host.substr(0, host.length -1) : host;

export const config : Config = {
    metadata: {
        ignore: ['**/node_modules/**'],
        entryFile: [
            path.join(getRootDirPath(), '..', 'common', 'src', 'domains', '**', '*.ts'),
            path.join(getRootDirPath(), 'src', 'app', 'auth', 'http', 'controllers', '**', '*.ts'),
            path.join(getRootDirPath(), 'src', 'app', 'chat', 'http', 'controllers', '**', '*.ts'),
        ]
    },
    decorator: {
        useBuildIn: true,
        useLibrary: [
            "@decorators/express"
        ]
    },
    swagger: {
        yaml: true,
        host,
        name: 'Chamesu - API Documentation',
        description: packageJson.description,
        basePath: '/',
        version: packageJson.version,
        outputDirectory: getWritableDirPath(),
        securityDefinitions: {
            Bearer: {
                name: 'Bearer',
                type: 'apiKey',
                in: 'header'
            },
            User: {
                type: 'oauth2',
                flows: {
                    password: {
                        tokenUrl: env.apiUrl + 'auth/token'
                    }
                }
            },
            Basic: {
                type: 'http',
                schema: 'basic'
            }
        },
        consumes: ['application/json'],
        produces: ['application/json']
    }
}

export async function generateSwaggerDocumentation() {
    return await generateDocumentation(config, tsConfig);
}
