import { Injectable } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Guest } from '../entities/guest.entity';
import { CreateGuestDto } from '../api/dto/create-guest.dto';
import { UpdateRsvpDto } from '../api/dto/update-rsvp.dto';

@Injectable()
export class GuestService {
  constructor(
    private readonly orm: MikroORM,
    private readonly eventEmitter: EventEmitter2,
  ) {}

  private get em() {
    return this.orm.em.fork();
  }

  async createGuest(tenantId: string, dto: CreateGuestDto): Promise<Guest> {
    const guest = this.em.create(Guest, {
      tenantId,
      ...dto,
    } as any);
    this.em.persist(guest);
    await this.em.flush();
    this.eventEmitter.emit('guest.invited', { guest });
    return guest;
  }

  async updateRsvp(tenantId: string, guestId: string, dto: UpdateRsvpDto): Promise<Guest | null> {
    const guest = await this.em.findOne(Guest, { tenantId, id: guestId });
    if (!guest) return null;
    guest.rsvp = dto.rsvp;
    if (dto.tableId) {
      guest.tableId = dto.tableId;
    }
    this.em.persist(guest);
    await this.em.flush();
    this.eventEmitter.emit('guest.rsvp', { guest });
    return guest;
  }

  async listGuests(tenantId: string): Promise<Guest[]> {
    return this.em.find(Guest, { tenantId });
  }
}
