import {and, eq, isNull} from 'drizzle-orm'

import {db, schema, type DbOrTx} from '../db/client'

type EventRow = typeof schema.events.$inferSelect

type EventInput = {
  name: string
  placeId: string | null
  startsAt: Date | null
  endsAt: Date | null
  url: string | null
}

// canonical events dedup on (venue, name, start); occurrences are rows
export const getOrCreateEvent = async (
  input: EventInput,
  executor: DbOrTx = db,
): Promise<EventRow> => {
  const [existing] = await executor
    .select()
    .from(schema.events)
    .where(
      and(
        input.placeId
          ? eq(schema.events.placeId, input.placeId)
          : isNull(schema.events.placeId),
        eq(schema.events.name, input.name),
        input.startsAt
          ? eq(schema.events.startsAt, input.startsAt)
          : isNull(schema.events.startsAt),
      ),
    )
    .limit(1)
  if (existing) return existing

  const [event] = await executor
    .insert(schema.events)
    .values(input)
    .returning()
  if (!event) throw new Error('failed to create event')
  return event
}
