import { AuthenticationError } from "@/errors/AuthenticationError";
import type { Context } from "elysia";
import { env } from "@/env";

const API_KEY_HEADER = "x-api-key";

export const apiKeyMiddleware = ({ headers }: Context) => {
    if (!isApiKeyRequired()) {
        return;
    }

    const apiKey = headers[API_KEY_HEADER];
    if (!apiKey) {
        throw new AuthenticationError("No API KEY provided");
    }

    if (!validateApiKey(apiKey)) {
        throw new AuthenticationError("Invalid API key");
    }
};

function isApiKeyRequired(): boolean {
    return Boolean(env.PRIMARY_API_KEY) || Boolean(env.SECONDARY_API_KEY);
}

function validateApiKey(apiKey: string): boolean {
    return apiKey === env.PRIMARY_API_KEY || apiKey === env.SECONDARY_API_KEY;
}
