import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

export type BookingEventType =
  | 'booking.record.created'
  | 'booking.record.updated'
  | 'booking.record.confirmed'
  | 'booking.record.cancelled'
  | 'booking.record.completed'
  | 'booking.record.noshow'
  | 'booking.group_event.created'
  | 'booking.group_event.updated'
  | 'booking.group_event.cancelled'
  | 'booking.client.created'
  | 'booking.membership.activated'
  | 'booking.membership.depleted'
  | 'booking.membership.expired'
  | 'booking.payment.completed'
  | 'booking.service.created'
  | 'booking.service.updated'
  | 'booking.staff.schedule_changed';

export interface BookingEventPayload {
  clubId: string;
  event: BookingEventType;
  data: Record<string, unknown>;
  userId?: string;
  timestamp: Date;
}

@Injectable()
export class BookingEventsService {
  constructor(private readonly emitter: EventEmitter2) {}

  async emit(event: BookingEventType, payload: Omit<BookingEventPayload, 'event' | 'timestamp'>) {
    const full: BookingEventPayload = {
      ...payload,
      event,
      timestamp: new Date(),
    };

    // Emit specific event (e.g. 'booking.record.created')
    await this.emitter.emitAsync(event, full);

    // Emit wildcard for webhook dispatcher (catches all booking events)
    await this.emitter.emitAsync('booking.*', full);
  }
}
