import { getServerSession } from "next-auth";
import type { Session } from "next-auth";
import { authOptions } from "@/lib/auth/authOptions";

/** True when API routes should accept requests as the dev bypass user (next dev only). */
export function isProjectAuthBypassEnabled(): boolean {
  return (
    process.env.NODE_ENV === "development" &&
    process.env.NEXT_PUBLIC_DEV_BYPASS_PROJECT_AUTH === "true"
  );
}

/** Email used for ownership checks when bypass is on; must match fs_users.data->>'email' for your projects. */
export function devBypassSessionEmail(): string | null {
  const email = (
    process.env.DEV_BYPASS_USER_EMAIL ||
    process.env.NEXT_PUBLIC_DEV_LOCAL_AUTH_EMAIL ||
    ""
  ).trim();
  return email || null;
}

/**
 * Drop-in replacement for getServerSession(authOptions) on API routes.
 * In development with NEXT_PUBLIC_DEV_BYPASS_PROJECT_AUTH=true, returns a synthetic session
 * so you can use the app without Google/cookies when DATABASE_URL works.
 */
export async function authSession(): Promise<Session | null> {
  const session = await getServerSession(authOptions);
  if (session?.user?.email) return session;
  if (!isProjectAuthBypassEnabled()) return session;
  const email = devBypassSessionEmail();
  if (!email) return session;
  return {
    expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
    user: {
      id: "dev-bypass",
      email,
      name: "Dev bypass",
    },
  };
}
