import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { PrismaService } from '../../prisma.service.js';
import { WechatNotifyService } from '../wechat-notify/wechat-notify.service.js';

interface TaskEventPayload {
  taskId: number;
  hospitalId: number;
  actorId: number;
  status: string;
}

/**
 * 任务事件监听器：订阅任务状态变化并触发微信推送。
 */
@Injectable()
export class TaskEventsListener {
  private readonly logger = new Logger(TaskEventsListener.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly wechatNotifyService: WechatNotifyService,
  ) {}

  /**
   * 任务发布事件：通知创建人和已绑定 openId 的接收工程师（如有）。
   */
  @OnEvent('task.published', { async: true })
  async onTaskPublished(payload: TaskEventPayload) {
    await this.dispatchTaskEvent('task.published', payload);
  }

  /**
   * 任务接收事件。
   */
  @OnEvent('task.accepted', { async: true })
  async onTaskAccepted(payload: TaskEventPayload) {
    await this.dispatchTaskEvent('task.accepted', payload);
  }

  /**
   * 任务完成事件。
   */
  @OnEvent('task.completed', { async: true })
  async onTaskCompleted(payload: TaskEventPayload) {
    await this.dispatchTaskEvent('task.completed', payload);
  }

  /**
   * 任务取消事件。
   */
  @OnEvent('task.cancelled', { async: true })
  async onTaskCancelled(payload: TaskEventPayload) {
    await this.dispatchTaskEvent('task.cancelled', payload);
  }

  /**
   * 工程师取消接收事件。
   */
  @OnEvent('task.released', { async: true })
  async onTaskReleased(payload: TaskEventPayload) {
    await this.dispatchTaskEvent('task.released', payload);
  }

  /**
   * 统一处理任务事件并派发通知目标。
   */
  private async dispatchTaskEvent(event: string, payload: TaskEventPayload) {
    const task = await this.prisma.task.findUnique({
      where: { id: payload.taskId },
      select: {
        id: true,
        creator: { select: { id: true, openId: true } },
        engineer: { select: { id: true, openId: true } },
      },
    });

    if (!task) {
      this.logger.warn(`任务事件监听未找到任务：taskId=${payload.taskId}`);
      return;
    }

    await this.wechatNotifyService.notifyTaskChange(
      [task.creator.openId, task.engineer?.openId],
      {
        event,
        taskId: payload.taskId,
        hospitalId: payload.hospitalId,
        actorId: payload.actorId,
        status: payload.status,
      },
    );
  }
}
