import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import {
  MODERATION_AUDIT_LOG_REPOSITORY,
  type IModerationAuditLogRepository,
  type ModerationAuditLogListResult,
} from '../../../domain/repositories/moderation-audit-log.repository';
import { GetModerationAuditLogsQuery } from './get-moderation-audit-logs.query';

@QueryHandler(GetModerationAuditLogsQuery)
export class GetModerationAuditLogsHandler
  implements IQueryHandler<GetModerationAuditLogsQuery>
{
  constructor(
    @Inject(MODERATION_AUDIT_LOG_REPOSITORY)
    private readonly repo: IModerationAuditLogRepository,
    private readonly logger: LoggerService,
  ) {}

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