import { Inject, Injectable, BadRequestException } from '@nestjs/common';
import { TravelRuleRecord } from '../../domain/entities/travel-rule-record.entity';
import {
  TRAVEL_RULE_REPOSITORY,
  ITravelRuleRepository,
} from '../../domain/repositories/travel-rule.repository.interface';

@Injectable()
export class TravelRuleService {
  constructor(
    @Inject(TRAVEL_RULE_REPOSITORY)
    private readonly repo: ITravelRuleRepository,
  ) {}

  /**
   * Check if a transfer requires Travel Rule compliance (>= $3,000).
   * Both sender and receiver must have KYC L2+.
   */
  async checkAndRecord(data: {
    transactionId: string;
    senderId: string;
    receiverId: string;
    amount: number;
    senderName?: string;
    receiverName?: string;
    senderKycLevel: number;
    receiverKycLevel: number;
  }): Promise<TravelRuleRecord | null> {
    if (data.amount < 3000) return null; // Below threshold

    if (data.senderKycLevel < 2 || data.receiverKycLevel < 2) {
      throw new BadRequestException(
        'Both parties must have KYC Level 2+ for transfers >= $3,000',
      );
    }

    const record = this.repo.create({
      transactionId: data.transactionId,
      senderId: data.senderId,
      receiverId: data.receiverId,
      amount: String(data.amount),
      senderName: data.senderName || null,
      receiverName: data.receiverName || null,
      senderKycLevel: data.senderKycLevel,
      receiverKycLevel: data.receiverKycLevel,
      status: 'completed',
    });
    return this.repo.save(record);
  }

  async getByTransactionId(transactionId: string) {
    return this.repo.findByTransactionId(transactionId);
  }
}
