import { Injectable } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
import { NotificationRule } from '../entities/notification-rule.entity';

@Injectable()
export class NotificationRuleService {
  constructor(private readonly orm: MikroORM) {}

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

  async getRulesForEvent(tenantId: string, module: string, event: string): Promise<NotificationRule[]> {
    return this.em.find(NotificationRule, { tenantId, module, event });
  }

  async createRule(tenantId: string, rule: Partial<NotificationRule>): Promise<NotificationRule> {
    const entity = this.em.create(NotificationRule, {
      tenantId,
      ...rule,
    } as any);
    this.em.persist(entity);
    await this.em.flush();
    return entity;
  }
}
