import { Injectable } from '@nestjs/common';
import { MikroORM } from '@mikro-orm/core';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { TodoItem } from '../entities/todo.entity';

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

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

  async createTodo(tenantId: string, dto: Partial<TodoItem>): Promise<TodoItem> {
    const todo = this.em.create(TodoItem, {
      tenantId,
      ...dto,
    } as any);
    this.em.persist(todo);
    await this.em.flush();
    this.eventEmitter.emit('todo.created', { todo });
    return todo;
  }

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

  async markComplete(tenantId: string, id: string): Promise<TodoItem | null> {
    const todo = await this.em.findOne(TodoItem, { tenantId, id });
    if (!todo) return null;
    todo.completed = true;
    this.em.persist(todo);
    await this.em.flush();
    this.eventEmitter.emit('todo.completed', { todo });
    return todo;
  }
}
