import { env } from "../env.js";
import { sessionAuth } from "./sessionAuth.js";
import { manageBearerAuth } from "./manageAuth.js";
import { createApiError } from "@inkeep/agents-core";

//#region src/middleware/workAppsAuth.ts
/**
* Work Apps Authentication Middleware
*
* Shared session/bearer token auth for protected work app routes (Slack, GitHub, etc.).
* Most work app routes are unauthenticated (events, commands, webhooks),
* but workspace management and user endpoints require session auth.
*
* Auth flow:
* 1. Test environment → bypass
* 2. Dev localhost → bypass with dev-user context
* 3. Bearer token → manageBearerAuth (bypass secret, session, Slack JWT, internal service)
* 4. Session cookie → sessionAuth
*/
const isTestEnvironment = () => env.ENVIRONMENT === "test";
const workAppsAuth = async (c, next) => {
	if (isTestEnvironment()) {
		await next();
		return;
	}
	if (env.ENVIRONMENT === "development") {
		const origin = c.req.header("Origin");
		if (origin) try {
			const originUrl = new URL(origin);
			if (originUrl.hostname === "localhost" || originUrl.hostname === "127.0.0.1") {
				const sessionUser = c.get("user");
				const session = c.get("session");
				if (sessionUser?.id) {
					c.set("userId", sessionUser.id);
					c.set("userEmail", sessionUser.email);
					c.set("tenantId", session?.activeOrganizationId || "default");
					c.set("tenantRole", "owner");
				} else {
					c.set("userId", "dev-user");
					c.set("tenantId", "default");
					c.set("tenantRole", "owner");
				}
				await next();
				return;
			}
		} catch {}
	}
	if (c.req.header("Authorization")?.startsWith("Bearer ")) return manageBearerAuth()(c, next);
	await sessionAuth()(c, async () => {
		const session = c.get("session");
		if (!session?.activeOrganizationId) throw createApiError({
			code: "forbidden",
			message: "No active organization selected. Please select an organization first."
		});
		c.set("tenantId", session.activeOrganizationId);
		await next();
	});
};

//#endregion
export { workAppsAuth };