import { NextRequest } from "next/server";
import { queryRaw } from "./db";

export interface CurrentUser {
  id: number;
  name: string;
  email: string;
}

export async function getCurrentUser(req: NextRequest): Promise<CurrentUser | null> {
  const email = req.headers.get("x-forwarded-user");

  // Dev fallback: no Traefik header → use participant id=1
  if (!email) {
    if (process.env.NODE_ENV === "development") {
      const rows = await queryRaw<CurrentUser>(`SELECT id, name, email FROM participants WHERE id = 1`);
      return rows[0] || null;
    }
    return null;
  }

  const rows = await queryRaw<CurrentUser>(
    `SELECT id, name, COALESCE(email, '') as email FROM participants WHERE email = $1`,
    [email]
  );
  return rows[0] || null;
}
