import mongoose from 'mongoose'
import Event from '../models/event.js'
import { connectDB } from './mongoose.js'
import { getOptionalMember } from './auth.js'

/**
 * Load an event by ObjectId or slug for public (non-admin) endpoints.
 * Enforces the isVisible gate: hidden events 404 for everyone except admins.
 *
 * @param {Object} reqEvent - h3 event (for auth/cookie access)
 * @param {String} identifier - ObjectId string or slug
 * @param {Object} [options]
 * @param {Boolean} [options.lean] - apply .lean() to the query
 * @param {String} [options.select] - apply .select() to the query
 * @returns {Promise<Object>} the event document
 */
export async function loadPublicEvent(reqEvent, identifier, options = {}) {
  if (!identifier) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Event identifier is required'
    })
  }

  await connectDB()

  const { lean = false, select = null } = options

  const applyOptions = (query) => {
    if (select) query = query.select(select)
    if (lean) query = query.lean()
    return query
  }

  let eventDoc
  if (mongoose.Types.ObjectId.isValid(identifier)) {
    eventDoc = await applyOptions(Event.findById(identifier))
  }
  if (!eventDoc) {
    eventDoc = await applyOptions(Event.findOne({ slug: identifier }))
  }

  if (!eventDoc) {
    throw createError({ statusCode: 404, statusMessage: 'Event not found' })
  }

  if (eventDoc.isVisible === false) {
    const requester = await getOptionalMember(reqEvent)
    if (requester?.role !== 'admin') {
      throw createError({ statusCode: 404, statusMessage: 'Event not found' })
    }
  }

  return eventDoc
}
