import type { FraudAdapter, EarnCtx, FraudSignal, AdapterConfig } from '../types.js'

export const paymentInstrumentAdapter: FraudAdapter<EarnCtx> = {
  key: 'payment-instrument',
  points: ['EARN'],
  async evaluate(ctx: EarnCtx, _cfg: AdapterConfig): Promise<FraudSignal | null> {
    if (!ctx.cardFingerprintReferee) return null

    // Check if referrer's payment methods share the same card fingerprint as referee
    const referrerCards = await ctx.host.listReferrerCardFingerprints(ctx.referrerUserId)
    const referrerFingerprints = new Set(referrerCards.filter(Boolean))

    if (referrerFingerprints.has(ctx.cardFingerprintReferee)) {
      return {
        adapter: 'payment-instrument',
        action: 'block',
        codes: ['SHARED_CARD_FINGERPRINT'],
        detail: { fingerprintSuffix: ctx.cardFingerprintReferee.slice(-8) },
      }
    }

    // Check for referee using same card across multiple referral accounts (ring)
    const cnt = await ctx.host.countDistinctReferrersForRefereeCardFingerprint(
      ctx.cardFingerprintReferee,
      ctx.refereeUserId,
    )
    if (cnt > 0) {
      return {
        adapter: 'payment-instrument',
        action: 'flag',
        codes: ['CARD_SEEN_IN_OTHER_REFERRAL'],
        detail: { fingerprintSuffix: ctx.cardFingerprintReferee.slice(-8), otherReferrals: cnt },
      }
    }

    return null
  },
}
