import { env } from "../env.js";
import { getLogger, isInternalServiceToken, verifyInternalServiceAuthHeader } from "@inkeep/agents-core";
import { registerAuthzMeta } from "@inkeep/agents-core/middleware";
import { createMiddleware } from "hono/factory";
import { HTTPException } from "hono/http-exception";

//#region src/middleware/evalsAuth.ts
const logger = getLogger("eval-auth");
/**
* Middleware to authenticate API requests using Bearer token authentication
* First checks if token matches INKEEP_AGENTS_EVAL_API_BYPASS_SECRET,
*/
const evalApiKeyAuth = () => {
	const mw = createMiddleware(async (c, next) => {
		const authHeader = c.req.header("Authorization");
		if (!authHeader || !authHeader.startsWith("Bearer ")) {
			if (env.ENVIRONMENT === "development") {
				await next();
				return;
			}
			throw new HTTPException(401, { message: "Missing or invalid authorization header. Expected: Bearer <api_key>" });
		}
		const apiKey = authHeader.substring(7);
		if (env.INKEEP_AGENTS_EVAL_API_BYPASS_SECRET) {
			if (!authHeader || !authHeader.startsWith("Bearer ")) {
				console.log("[AUTH DEBUG] Rejecting: No Bearer token provided");
				throw new HTTPException(401, { message: "Missing or invalid authorization header. Expected: Bearer <api_key>" });
			}
			if (authHeader.substring(7) === env.INKEEP_AGENTS_EVAL_API_BYPASS_SECRET) {
				logger.info({}, "Bypass secret authenticated successfully");
				await next();
				return;
			}
		}
		if (isInternalServiceToken(apiKey)) {
			const result = await verifyInternalServiceAuthHeader(authHeader);
			if (!result.valid || !result.payload) throw new HTTPException(401, { message: result.error || "Invalid internal service token" });
			logger.info({
				serviceId: result.payload.sub,
				tenantId: result.payload.tenantId,
				projectId: result.payload.projectId
			}, "Internal service authenticated");
			await next();
			return;
		}
		if (env.ENVIRONMENT === "development") {
			await next();
			return;
		}
		throw new HTTPException(401, { message: "Invalid Token" });
	});
	registerAuthzMeta(mw, { description: "Requires eval API key (bypass secret or internal service token)" });
	return mw;
};

//#endregion
export { evalApiKeyAuth };