import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import {
  AUDIT_LOG_REPOSITORY,
  type IAuditLogRepository,
  type AuditLogListResult,
} from '../../../domain/repositories/audit-log.repository';
import { GetAuditLogsQuery } from './get-audit-logs.query';

@QueryHandler(GetAuditLogsQuery)
export class GetAuditLogsHandler implements IQueryHandler<GetAuditLogsQuery> {
  constructor(
    @Inject(AUDIT_LOG_REPOSITORY) private readonly auditRepo: IAuditLogRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetAuditLogsQuery): Promise<AuditLogListResult> {
    try {
      return await this.auditRepo.findAll({
        page: query.page,
        limit: query.limit,
        action: query.action,
        actorId: query.actorId,
        targetId: query.targetId,
        targetType: query.targetType,
        startDate: query.startDate,
        endDate: query.endDate,
      });
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get audit logs: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetAuditLogsHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy nhật ký kiểm toán');
    }
  }
}
