import type { inferAsyncReturnType } from '@trpc/server'
import type { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

/**
 * Create tRPC context for each request
 */
export async function createContext(opts?: FetchCreateContextFnOptions) {
  const session = await auth()

  // Extract IP and user agent from headers
  const ip = opts?.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? 'unknown'
  const userAgent = opts?.req.headers.get('user-agent') ?? 'unknown'

  return {
    session,
    prisma,
    ip,
    userAgent,
  }
}

export type Context = inferAsyncReturnType<typeof createContext>
