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

/**
 * IP reputation via pluggable provider interface.
 * Default: CF bot signals (cfBotScore on SignupCtx); no paid vendor by default.
 * CLICK point: uses existing ipHash only (no external call — AE-only logging).
 */
export const ipReputationAdapter: FraudAdapter<ClickCtx | SignupCtx> = {
  key: 'ip-reputation',
  points: ['CLICK', 'SIGNUP'],
  async evaluate(ctx: ClickCtx | SignupCtx, cfg: AdapterConfig): Promise<FraudSignal | null> {
    // No external call — CF bot score only on SIGNUP; CLICK is AE-only (no persist)
    if ('refereeUserId' in ctx) {
      const signupCtx = ctx as SignupCtx
      if (signupCtx.cfBotScore === undefined) return null
      const threshold = (cfg.params?.['datacenterBotScoreThreshold'] as number | undefined) ?? 10
      if (signupCtx.cfBotScore > threshold) return null
      return {
        adapter: 'ip-reputation',
        action: 'flag',
        codes: ['DATACENTER_IP_BOT_SCORE'],
        detail: { botScore: signupCtx.cfBotScore },
      }
    }
    // CLICK: flag only into AE — no DB persist (handled by touch.ts AE write)
    return null
  },
}
