import { RiskSeverity } from "@prisma/client";
import { prisma } from "@/server/db";
import { decimal, type Money } from "@/server/wallet/ledger";

export function scoreStakeRisk(input: { stake: Money; potentialPayout: Money; userDailyStake?: Money }) {
  const stake = decimal(input.stake);
  const payout = decimal(input.potentialPayout);
  const daily = input.userDailyStake ? decimal(input.userDailyStake) : decimal(0);

  let score = 0;
  if (stake.gte(500)) score += 25;
  if (stake.gte(2500)) score += 35;
  if (payout.gte(10000)) score += 30;
  if (daily.plus(stake).gte(5000)) score += 25;

  const severity =
    score >= 80 ? RiskSeverity.CRITICAL : score >= 50 ? RiskSeverity.HIGH : score >= 25 ? RiskSeverity.MEDIUM : RiskSeverity.LOW;

  return { score, severity };
}

export async function recordRiskIfNeeded(input: {
  userId: string;
  category: string;
  score: number;
  severity: RiskSeverity;
  reason: string;
  metadata?: object;
}) {
  if (input.score < 25) {
    return null;
  }

  return prisma.riskEvent.create({
    data: {
      userId: input.userId,
      category: input.category,
      score: input.score,
      severity: input.severity,
      reason: input.reason,
      metadata: input.metadata
    }
  });
}
