import consola from "consola";
import { config as configDotenv } from 'dotenv';

configDotenv();
export const config = {
    internal_port: parseInt(process.env.APP_PORT) || 4010,
    development: process.env.NODE_ENV === "production",
    version: process.env.VERSION || require('../package.json').version,
    eventname: process.env.EVENT_NAME || "Please set the event name",
    currency_symbol: process.env.CURRENCY_SYMBOL || "€",
    sponsoring_receipt_minimum_amount: process.env.SPONSORING_RECEIPT_MINIMUM_AMOUNT || "10",
    codeformat: process.env.CODEFORMAT || "qrcode",
    sponor_logos: getSponsorLogos(),
    api_key: getApiKey(),
    disclaimer_text: process.env.DISCLAIMER_TEXT || "",
    donations_footer_text: process.env.DONATIONS_FOOTER_TEXT || "",
    contracts_per_runner: parseInt(process.env.CONTRACTS_PER_RUNNER) || 1,
}
let errors = 0
if (typeof config.internal_port !== "number") {
    errors++
}
if (typeof config.contracts_per_runner !== "number") {
    errors++
}
if (typeof config.development !== "boolean") {
    errors++
}
function getSponsorLogos(): string[] {
    try {
        const logos = JSON.parse(process.env.SPONOR_LOGOS);
        if (!Array.isArray(logos)) { throw new Error("Not an array.") }
        return logos;
    } catch (error) {
        return ["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="];
    }
}

function getApiKey(): string {
    const key = process.env.API_KEY;
    if (!key) {
        consola.info("No API key set - generating a random one...");
        let result = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        const charactersLength = characters.length;
        for (var i = 0; i < 64; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        consola.info(`API KEY: ${result}`)
        return result;
    }
    if (key.length < 64) {
        consola.error(`API key is too short - minimum: 64, current: ${key.length}`)
        throw new Error("API_KEY too short.")
    }
    return key
}
export let e = errors