import { getSession, type SessionPayload } from "@/lib/session"

export class AuthError extends Error {
  readonly status: number

  constructor(status: number, message: string) {
    super(message)
    this.name = "AuthError"
    this.status = status
  }
}

/** Requires a valid session. Throws `AuthError` with status 401 if missing or invalid. */
export async function requireAuth(): Promise<SessionPayload> {
  const session = await getSession()
  if (!session) {
    throw new AuthError(401, "Unauthorized")
  }
  return session
}

/** Requires `admin` role. Throws 401 if not logged in, 403 if not admin. */
export async function requireAdmin(): Promise<SessionPayload> {
  const session = await requireAuth()
  if (session.role !== "admin") {
    throw new AuthError(403, "Forbidden")
  }
  return session
}
