import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { CreateFeedbackDto, UpdateFeedbackDto } from '../dto';
import {
  MessageNotFoundException,
  FeedbackExistsException,
  FeedbackNotFoundException,
  ConversationAccessDeniedException,
} from '../exceptions';

/**
 * 反馈服务
 */
@Injectable()
export class FeedbackService {
  private readonly logger = new Logger(FeedbackService.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 提交消息反馈
   */
  async createFeedback(
    messageId: string,
    dto: CreateFeedbackDto,
    userId: string,
  ) {
    // 验证消息存在
    const message = await this.prisma.aIMessage.findFirst({
      where: { id: messageId },
      include: {
        conversation: true,
        feedback: true,
      },
    });

    if (!message) {
      throw new MessageNotFoundException(messageId);
    }

    // 验证用户权限
    if (message.conversation.userId !== userId) {
      throw new ConversationAccessDeniedException();
    }

    // 检查是否已反馈
    if (message.feedback) {
      throw new FeedbackExistsException();
    }

    // 创建反馈
    const feedback = await this.prisma.aIMessageFeedback.create({
      data: {
        messageId,
        type: dto.type,
        comment: dto.comment,
      },
    });

    this.logger.log(`创建反馈: ${feedback.id}, 类型: ${dto.type}`);

    return {
      id: feedback.id,
      messageId: feedback.messageId,
      type: feedback.type,
      comment: feedback.comment,
      createdAt: feedback.createdAt,
    };
  }

  /**
   * 更新消息反馈
   */
  async updateFeedback(
    messageId: string,
    dto: UpdateFeedbackDto,
    userId: string,
  ) {
    // 验证消息存在
    const message = await this.prisma.aIMessage.findFirst({
      where: { id: messageId },
      include: {
        conversation: true,
        feedback: true,
      },
    });

    if (!message) {
      throw new MessageNotFoundException(messageId);
    }

    // 验证用户权限
    if (message.conversation.userId !== userId) {
      throw new ConversationAccessDeniedException();
    }

    // 检查反馈是否存在
    if (!message.feedback) {
      throw new FeedbackNotFoundException();
    }

    // 更新反馈
    const feedback = await this.prisma.aIMessageFeedback.update({
      where: { id: message.feedback.id },
      data: {
        type: dto.type,
        comment: dto.comment,
      },
    });

    this.logger.log(`更新反馈: ${feedback.id}`);

    return {
      id: feedback.id,
      messageId: feedback.messageId,
      type: feedback.type,
      comment: feedback.comment,
      createdAt: feedback.createdAt,
    };
  }

  /**
   * 获取消息反馈
   */
  async getFeedback(messageId: string, userId: string) {
    const message = await this.prisma.aIMessage.findFirst({
      where: { id: messageId },
      include: {
        conversation: true,
        feedback: true,
      },
    });

    if (!message) {
      throw new MessageNotFoundException(messageId);
    }

    if (message.conversation.userId !== userId) {
      throw new ConversationAccessDeniedException();
    }

    if (!message.feedback) {
      return null;
    }

    return {
      id: message.feedback.id,
      messageId: message.feedback.messageId,
      type: message.feedback.type,
      comment: message.feedback.comment,
      createdAt: message.feedback.createdAt,
    };
  }
}
