import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OperationLog } from '../entities/operation-log.entity';

@Injectable()
export class OperationLogsService {
  constructor(@InjectRepository(OperationLog) private repo: Repository<OperationLog>) {}

  async log(params: {
    userId?: number;
    username?: string;
    module: string;
    action: string;
    targetId?: number;
    targetType?: string;
    detail?: string;
    ipAddress?: string;
    userAgent?: string;
    status?: string;
  }) {
    const entry = this.repo.create(params);
    return this.repo.save(entry);
  }

  async findLatestDingTalkAttendancePull() {
    return this.repo
      .createQueryBuilder('log')
      .where('log.module = :module', { module: '考勤管理' })
      .andWhere('log.action IN (:...actions)', {
        actions: ['拉取钉钉课程考勤', '查看已拉取课程考勤', '钉钉考勤导入', '刷新钉钉考勤'],
      })
      .orderBy('log.createdAt', 'DESC')
      .getOne();
  }

  async findAll(query?: {
    module?: string;
    userId?: number;
    startDate?: string;
    endDate?: string;
    page?: number;
    pageSize?: number;
  }) {
    if (query?.startDate && query?.endDate && query.startDate > query.endDate) {
      throw new BadRequestException('结束日期不能早于开始日期');
    }
    const qb = this.repo.createQueryBuilder('log').orderBy('log.createdAt', 'DESC');
    if (query?.module) qb.andWhere('log.module = :module', { module: query.module });
    if (query?.userId) qb.andWhere('log.userId = :userId', { userId: query.userId });
    if (query?.startDate)
      qb.andWhere('log.createdAt >= :startDate', { startDate: query.startDate });
    if (query?.endDate)
      qb.andWhere('log.createdAt <= :endDate', { endDate: query.endDate + ' 23:59:59' });

    const page = query?.page || 1;
    const pageSize = query?.pageSize || 50;
    const [data, total] = await qb
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return { data, total, page, pageSize };
  }
}
