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

export const identityRingAdapter: FraudAdapter<EarnCtx> = {
  key: 'identity-ring',
  points: ['EARN'],
  async evaluate(ctx: EarnCtx, _cfg: AdapterConfig): Promise<FraudSignal | null> {
    // userId equality
    if (ctx.referrerUserId === ctx.refereeUserId) {
      return {
        adapter: 'identity-ring',
        action: 'block',
        codes: ['SELF_REFERRAL_USER_ID'],
        detail: { matchField: 'userId' },
      }
    }

    // Load phones + canonical emails
    const [referrer, referee] = await Promise.all([
      ctx.host.getUserIdentityRingFields(ctx.referrerUserId),
      ctx.host.getUserIdentityRingFields(ctx.refereeUserId),
    ])

    const referrerPhone = referrer?.phoneIndex
    const refereePhone = referee?.phoneIndex
    // CRITICAL: skip empty/null before equality — empty string matches empty string
    if (referrerPhone && refereePhone && referrerPhone === refereePhone) {
      return {
        adapter: 'identity-ring',
        action: 'block',
        codes: ['SELF_REFERRAL_PHONE'],
        detail: { matchField: 'phoneIndex' },
      }
    }

    const referrerCanonical = referrer?.emailCanonicalIndex
    const refereeCanonical = referee?.emailCanonicalIndex
    // CRITICAL: skip empty/null before equality
    if (referrerCanonical && refereeCanonical && referrerCanonical === refereeCanonical) {
      return {
        adapter: 'identity-ring',
        action: 'block',
        codes: ['SELF_REFERRAL_EMAIL_CANONICAL'],
        detail: { matchField: 'emailCanonicalIndex' },
      }
    }

    return null
  },
}
