import { cookies } from "next/headers";
import { AUTH_COOKIE, USER_COOKIE, type SessionUser } from "@/lib/auth/session";

export async function getSessionUser(): Promise<SessionUser | null> {
  const cookieStore = await cookies();
  if (cookieStore.get(AUTH_COOKIE)?.value !== "1") return null;

  const raw = cookieStore.get(USER_COOKIE)?.value;
  if (!raw) return null;

  try {
    const user = JSON.parse(raw) as SessionUser;
    if (!user?.id) return null;
    return user;
  } catch {
    return null;
  }
}

export async function requireSessionUser(): Promise<SessionUser> {
  const user = await getSessionUser();
  if (!user) throw new Error("Unauthorized");
  return user;
}
