import type { FraudAdapter, EarnCtx, SignupCtx, FraudSignal, AdapterConfig } from '../types.js'
import { eq } from 'drizzle-orm'
import { referralsTable } from '../../schema.js'

export const deviceFingerprintAdapter: FraudAdapter<EarnCtx | SignupCtx> = {
  key: 'device-fingerprint',
  points: ['SIGNUP', 'EARN'],
  async evaluate(ctx: EarnCtx | SignupCtx, _cfg: AdapterConfig): Promise<FraudSignal | null> {
    // EARN: check if referrer and referee share the same visitor_id
    if ('referralId' in ctx) {
      const earnCtx = ctx as EarnCtx
      if (!earnCtx.visitorIdReferee || !earnCtx.visitorIdReferrer) return null
      if (earnCtx.visitorIdReferee !== earnCtx.visitorIdReferrer) return null
      return {
        adapter: 'device-fingerprint',
        action: 'block',
        codes: ['SHARED_DEVICE_FINGERPRINT'],
        detail: { visitorId: earnCtx.visitorIdReferee.slice(-8) },
      }
    }

    // SIGNUP: check if current visitor_id appears on any existing referral as referrer
    const signupCtx = ctx as SignupCtx
    if (!signupCtx.visitorId) return null

    const existing = await signupCtx.db
      .select({ id: referralsTable.id, referrerUserId: referralsTable.referrerUserId })
      .from(referralsTable)
      .where(eq(referralsTable.visitorIdReferrer, signupCtx.visitorId))
      .limit(1)

    if (!existing.length) return null

    return {
      adapter: 'device-fingerprint',
      action: 'flag',
      codes: ['DEVICE_SEEN_AS_REFERRER'],
      detail: { visitorId: signupCtx.visitorId.slice(-8) },
    }
  },
}
