export interface EventMedia {
  id: number
  name: string | null
  url: string | null
}

export interface CompanyEvent {
  id: number
  title: string
  description: string | null
  date: string | null
  time: string | null
  type: 'cultura' | 'esporte'
  cover_url: string | null
  order: number
  media: EventMedia[]
}

interface ApiResponse<T> {
  payload: T
}

export const useEvents = () => {
  const { apiUrl } = useRuntimeConfig().public

  const { data: eventsData } = useAsyncData('company-events', () =>
    $fetch<ApiResponse<CompanyEvent[]>>(`${apiUrl}/api/company-events`).catch(() => null),
  )

  const events = computed<CompanyEvent[]>(() => {
    const payload = eventsData.value?.payload
    if (!Array.isArray(payload)) return []
    return payload
  })

  return { events }
}

const MONTHS = [
  'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho',
  'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro',
]

export const formatEventDateTime = (event: Pick<CompanyEvent, 'date' | 'time'>): string => {
  const parts: string[] = []

  if (event.date) {
    const [year, month, day] = event.date.split('-')
    const monthName = MONTHS[Number(month) - 1]
    if (monthName && day && year) parts.push(`${Number(day)} de ${monthName} de ${year}`)
  }

  if (event.time) parts.push(`${event.time}h`)

  return parts.join(' · ')
}

export const eventTypeLabel = (type: CompanyEvent['type']): string =>
  type === 'esporte' ? 'Esporte' : 'Cultura'
