export type OAuthProvider = "google" | "microsoft" | "github";

export type OAuthCredentials = {
	clientId: string;
	clientSecret: string;
};

export type Env = {
	nodeEnv: string;
	allowDevAuth: boolean;
	cookieSecure: boolean;
	appOrigin: string;
	oauth: Partial<Record<OAuthProvider, OAuthCredentials>>;
};

function credentials(
	source: Record<string, string | undefined>,
	idKey: string,
	secretKey: string,
): OAuthCredentials | undefined {
	const clientId = source[idKey];
	const clientSecret = source[secretKey];
	if (!clientId || !clientSecret) return undefined;
	return { clientId, clientSecret };
}

export function loadEnv(
	source: Record<string, string | undefined> = process.env,
): Env {
	const nodeEnv = source.NODE_ENV ?? "development";
	const allowDevAuth =
		source.ALLOW_DEV_AUTH === "1" || source.ALLOW_DEV_AUTH === "true";

	if (nodeEnv === "production" && allowDevAuth) {
		throw new Error("ALLOW_DEV_AUTH is forbidden in production");
	}

	return {
		nodeEnv,
		allowDevAuth,
		cookieSecure: nodeEnv === "production",
		appOrigin: source.APP_ORIGIN ?? "http://localhost:8787",
		oauth: {
			google: credentials(
				source,
				"OAUTH_GOOGLE_CLIENT_ID",
				"OAUTH_GOOGLE_CLIENT_SECRET",
			),
			microsoft: credentials(
				source,
				"OAUTH_MICROSOFT_CLIENT_ID",
				"OAUTH_MICROSOFT_CLIENT_SECRET",
			),
			github: credentials(
				source,
				"OAUTH_GITHUB_CLIENT_ID",
				"OAUTH_GITHUB_CLIENT_SECRET",
			),
		},
	};
}
