import type { FraudAdapter, EarnCtx, FraudSignal, AdapterConfig } from '../types.js';
import { eq } from 'drizzle-orm';
import { users } from '@/server/db/schema.js';

export const phoneRequiredEarnAdapter: FraudAdapter<EarnCtx> = {
  key: 'phone-required-earn',
  points: ['EARN'],
  async evaluate(ctx: EarnCtx, _cfg: AdapterConfig): Promise<FraudSignal | null> {
    // Load phones for both parties if not in ctx
    const [referrer, referee] = await Promise.all([
      ctx.db.select({ phoneIndex: users.phoneIndex }).from(users).where(eq(users.id, ctx.referrerUserId)).limit(1),
      ctx.db.select({ phoneIndex: users.phoneIndex }).from(users).where(eq(users.id, ctx.refereeUserId)).limit(1),
    ]);

    const referrerPhone = referrer[0]?.phoneIndex;
    const refereePhone = referee[0]?.phoneIndex;

    if (!referrerPhone || !refereePhone) {
      return {
        adapter: 'phone-required-earn',
        action: 'block',
        codes: ['MISSING_VERIFIED_PHONE'],
        detail: { referrerHasPhone: !!referrerPhone, refereeHasPhone: !!refereePhone },
      };
    }

    // Same phone number on both accounts
    if (referrerPhone === refereePhone) {
      return {
        adapter: 'phone-required-earn',
        action: 'block',
        codes: ['SHARED_PHONE_NUMBER'],
        detail: {},
      };
    }

    return null;
  },
};
