import { Decimal } from '@prisma/client/runtime/library';

export type CashbackRuleRow = {
  targetType: string;
  targetId: bigint | null;
  rate: Decimal;
  marketType: string | null;
};

const TARGET_PRIORITY: Record<string, number> = {
  USER: 3,
  AGENT: 2,
  GLOBAL: 1,
};

export function resolveCashbackRateForBet(params: {
  userId: bigint;
  agentId: bigint | null;
  marketTypes: string[];
  agentDefaultRate: Decimal;
  rules: CashbackRuleRow[];
}): Decimal {
  const { userId, agentId, marketTypes, agentDefaultRate, rules } = params;
  let best: { priority: number; rate: Decimal } | null = null;

  for (const rule of rules) {
    if (rule.marketType && !marketTypes.includes(rule.marketType)) continue;

    let priority = 0;
    if (rule.targetType === 'USER' && rule.targetId?.toString() === userId.toString()) {
      priority = TARGET_PRIORITY.USER;
    } else if (
      rule.targetType === 'AGENT' &&
      agentId != null &&
      rule.targetId?.toString() === agentId.toString()
    ) {
      priority = TARGET_PRIORITY.AGENT;
    } else if (rule.targetType === 'GLOBAL') {
      priority = TARGET_PRIORITY.GLOBAL;
    } else {
      continue;
    }

    if (!best || priority > best.priority) {
      best = { priority, rate: rule.rate };
    }
  }

  return best?.rate ?? agentDefaultRate;
}
