import type { FraudAdapter, EarnCtx, FraudSignal, AdapterConfig } from '../types.js';
import { eq } from 'drizzle-orm';
import { users } from '@/server/db/schema.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.db.select({ phoneIndex: users.phoneIndex, emailCanonicalIndex: users.emailCanonicalIndex })
        .from(users).where(eq(users.id, ctx.referrerUserId)).limit(1),
      ctx.db.select({ phoneIndex: users.phoneIndex, emailCanonicalIndex: users.emailCanonicalIndex })
        .from(users).where(eq(users.id, ctx.refereeUserId)).limit(1),
    ]);

    const referrerPhone = referrer[0]?.phoneIndex;
    const refereePhone = referee[0]?.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[0]?.emailCanonicalIndex;
    const refereeCanonical = referee[0]?.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;
  },
};
