import 'server-only'

import { NextResponse } from 'next/server'
import { getSessionUser, getMyParticipant } from '@/lib/auth'
import type { SessionUser } from '@/lib/auth'
import type { TripParticipant } from '@/types/db'

export type Guard =
  | { ok: true; user: SessionUser; participant: TripParticipant }
  | { ok: false; response: NextResponse }

/** Require a signed-in user who is an active participant on the trip. */
export async function requireParticipant(tripId: string): Promise<Guard> {
  const user = await getSessionUser()
  if (!user) {
    return { ok: false, response: NextResponse.json({ error: 'Sign in first.' }, { status: 401 }) }
  }
  const participant = await getMyParticipant(tripId)
  if (!participant) {
    return {
      ok: false,
      response: NextResponse.json({ error: 'You are not a participant on this trip.' }, { status: 403 }),
    }
  }
  return { ok: true, user, participant }
}
