import { Injectable, Inject, Logger } from '@nestjs/common';
import {
  AI_AGENT_CLIENT,
  IAiAgentClient,
  AgentAnomalyRequest,
} from '../../domain/ports/ai-agent.client.interface';
import { AnomalyDetectRequestDto, AnomalyDetectResponseDto } from '../../interface/http/dto/anomaly.dto';

@Injectable()
export class AiAnomalyService {
  private readonly logger = new Logger(AiAnomalyService.name);

  constructor(
    @Inject(AI_AGENT_CLIENT) private readonly agentClient: IAiAgentClient,
  ) {}

  async check(req: AnomalyDetectRequestDto): Promise<AnomalyDetectResponseDto> {
    const agentReq: AgentAnomalyRequest = {
      userId: req.userId,
      transactionType: req.transactionType,
      amount: req.amount,
      metadata: req.metadata,
    };

    try {
      const raw = await this.agentClient.anomalyDetect(agentReq);
      return {
        isAnomalous: raw.isAnomalous,
        riskScore: raw.riskScore,
        reasons: raw.reasons,
      };
    } catch (error) {
      this.logger.warn(`External AI anomaly detection unavailable: ${error.message}`);
    }

    // Fallback: simple rule-based anomaly detection
    return this.localAnomalyCheck(req);
  }

  private localAnomalyCheck(req: AnomalyDetectRequestDto): AnomalyDetectResponseDto {
    const reasons: string[] = [];
    let riskScore = 0;

    if (req.amount >= 10000) {
      reasons.push('Large transaction amount');
      riskScore += 40;
    }
    if (req.amount >= 2500 && req.amount < 3000) {
      reasons.push('Near structuring threshold');
      riskScore += 30;
    }

    return {
      isAnomalous: riskScore >= 50,
      riskScore: Math.min(100, riskScore),
      reasons,
    };
  }
}
