import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { DesktopOpActionLogEntity } from '../entity/desktop_op_action_log.js';

/** desktop_op 操作日志查询服务（只读，日志不允许从后台修改） */
@Provide()
@Scope(ScopeEnum.Singleton)
export class DesktopOpActionLogService {
  @InjectEntityModel(DesktopOpActionLogEntity)
  logRepo!: Repository<DesktopOpActionLogEntity>;

  /**
   * 分页查询操作日志
   * @param params 过滤参数：应用 id、渠道 id、状态、时间范围
   */
  async page(params: {
    page?: number;
    size?: number;
    appId?: string;
    channelId?: number;
    status?: string;
    from?: number;
    to?: number;
  }) {
    const { page = 1, size = 20, appId, channelId, status, from, to } = params;
    const qb = this.logRepo.createQueryBuilder('log');
    // 按应用 id 过滤
    if (appId) qb.andWhere('log.appId = :appId', { appId });
    // 按渠道 id 过滤
    if (channelId) qb.andWhere('log.channelId = :channelId', { channelId });
    // 按状态过滤
    if (status) qb.andWhere('log.status = :status', { status });
    // 按起始时间戳（毫秒）过滤
    if (from) qb.andWhere('log.createTime >= :from', { from: new Date(from) });
    // 按截止时间戳（毫秒）过滤
    if (to) qb.andWhere('log.createTime <= :to', { to: new Date(to) });
    // 按创建时间倒序排列并分页
    qb.orderBy('log.createTime', 'DESC')
      .skip((page - 1) * size)
      .take(size);
    const [list, total] = await qb.getManyAndCount();
    return { list, pagination: { page, size, total } };
  }

  /** 查询单条日志详情 */
  async info(id: number) {
    return this.logRepo.findOneBy({ id });
  }
}
