import { Signal, SignalStatus } from "@prisma/client";

type EventScore = {
  homeScore: number;
  awayScore: number;
};

function evaluate1X2(selection: string, score: EventScore): SignalStatus {
  const normalized = selection.trim().toUpperCase();
  if (score.homeScore === score.awayScore) return normalized === "X" ? SignalStatus.win : SignalStatus.lose;
  const homeWon = score.homeScore > score.awayScore;
  if (normalized === "1") return homeWon ? SignalStatus.win : SignalStatus.lose;
  if (normalized === "2") return homeWon ? SignalStatus.lose : SignalStatus.win;
  return SignalStatus.manual_review;
}

function evaluateTotal(selection: string, lineValue: number | null, score: EventScore): SignalStatus {
  if (lineValue === null) return SignalStatus.manual_review;
  const total = score.homeScore + score.awayScore;
  const normalized = selection.trim().toLowerCase();
  if (total === lineValue) return SignalStatus.void;
  if (normalized.includes("over")) return total > lineValue ? SignalStatus.win : SignalStatus.lose;
  if (normalized.includes("under")) return total < lineValue ? SignalStatus.win : SignalStatus.lose;
  return SignalStatus.manual_review;
}

function evaluateBtts(selection: string, score: EventScore): SignalStatus {
  const bothScored = score.homeScore > 0 && score.awayScore > 0;
  const normalized = selection.trim().toLowerCase();
  if (normalized.includes("yes")) return bothScored ? SignalStatus.win : SignalStatus.lose;
  if (normalized.includes("no")) return bothScored ? SignalStatus.lose : SignalStatus.win;
  return SignalStatus.manual_review;
}

function evaluateHandicap(selection: string, lineValue: number | null, score: EventScore): SignalStatus {
  if (lineValue === null) return SignalStatus.manual_review;
  const normalized = selection.trim().toLowerCase();
  const isHome = normalized.includes("1") || normalized.includes("home");
  const value = isHome ? score.homeScore + lineValue - score.awayScore : score.awayScore + lineValue - score.homeScore;
  if (value === 0) return SignalStatus.void;
  return value > 0 ? SignalStatus.win : SignalStatus.lose;
}

export function settleSignal(signal: Signal, score: EventScore) {
  const market = signal.marketType.trim().toLowerCase();
  if (market === "1x2") return evaluate1X2(signal.selection, score);
  if (market.includes("total")) return evaluateTotal(signal.selection, signal.lineValue, score);
  if (market.includes("both teams to score") || market.includes("btts")) return evaluateBtts(signal.selection, score);
  if (market.includes("handicap")) return evaluateHandicap(signal.selection, signal.lineValue, score);
  return SignalStatus.manual_review;
}

