import type { TenantEvent } from '../../api';
import { isPastEvent } from '../eventDate';

export type EventStatusKey = 'all' | 'upcoming' | 'draft' | 'past';

export function resolveEventStatusKey(event: TenantEvent): Exclude<EventStatusKey, 'all'> {
  if (event.status === 'draft') {
    return 'draft';
  }
  if (event.status === 'published') {
    if (event.event_date && isPastEvent(event.event_date)) {
      return 'past';
    }
    return 'upcoming';
  }
  if (event.event_date && isPastEvent(event.event_date)) {
    return 'past';
  }
  return 'upcoming';
}

export function buildEventStatusCounts(events: TenantEvent[]): Record<EventStatusKey, number> {
  const counts: Record<EventStatusKey, number> = {
    all: events.length,
    upcoming: 0,
    draft: 0,
    past: 0,
  };

  events.forEach((event) => {
    const key = resolveEventStatusKey(event);
    counts[key] += 1;
  });

  return counts;
}

export function filterEventsByStatus(events: TenantEvent[], status: EventStatusKey): TenantEvent[] {
  if (status === 'all') {
    return events;
  }
  return events.filter((event) => resolveEventStatusKey(event) === status);
}
