import { GenericCrudService } from '@/server/utils/generic-crud.service';
import { DataSource } from 'typeorm';
import { ChatMessage } from './chat-message.entity';

export class ChatMessageService extends GenericCrudService<ChatMessage> {
  constructor(dataSource: DataSource) {
    super(dataSource, ChatMessage, {
      userTracking: {
        createdByField: 'createdBy',
        updatedByField: 'updatedBy'
      }
    });
  }

  /**
   * 根据课堂ID获取聊天消息历史记录
   * @param classId 课堂ID
   * @param page 页码
   * @param pageSize 每页数量
   * @returns 聊天消息列表和总数
   */
  async getHistoryByClassId(
    classId: string,
    page: number = 1,
    pageSize: number = 50
  ): Promise<[ChatMessage[], number]> {
    return this.getList(
      page,
      pageSize,
      undefined,
      undefined,
      { classId },
      [],
      { timestamp: 'DESC' }
    );
  }

  /**
   * 获取最新的聊天消息
   * @param classId 课堂ID
   * @param limit 限制数量
   * @returns 最新的聊天消息列表
   */
  async getLatestMessages(classId: string, limit: number = 20): Promise<ChatMessage[]> {
    const [messages] = await this.getList(
      1,
      limit,
      undefined,
      undefined,
      { classId },
      [],
      { timestamp: 'DESC' }
    );
    return messages;
  }

  /**
   * 创建聊天消息
   * @param data 消息数据
   * @param userId 用户ID
   * @returns 创建的聊天消息
   */
  async createMessage(data: Partial<ChatMessage>, userId?: number): Promise<ChatMessage> {
    return this.create(data, userId);
  }

  /**
   * 批量创建聊天消息
   * @param messages 消息数据数组
   * @param userId 用户ID
   * @returns 创建的聊天消息数组
   */
  async createMessages(messages: Partial<ChatMessage>[], userId?: number): Promise<ChatMessage[]> {
    const results: ChatMessage[] = [];
    for (const message of messages) {
      const result = await this.create(message, userId);
      results.push(result);
    }
    return results;
  }
}