import type { Position, EventType } from "@prisma/client";

export const DEFAULT_RULES: Record<string, Partial<Record<string, number>>> = {
  GK: {
    GOAL: 10, ASSIST: 3, YELLOW_CARD: -1, RED_CARD: -3, SECOND_YELLOW: -3,
    CLEAN_SHEET: 6, PENALTY_SAVED: 5, PENALTY_MISSED: -2, OWN_GOAL: -2,
    MOTM: 3, EXTRA_TIME_BONUS: 1, INJURY_NO_SUB: -1,
  },
  DEF: {
    GOAL: 8, ASSIST: 3, YELLOW_CARD: -1, RED_CARD: -3, SECOND_YELLOW: -3,
    CLEAN_SHEET: 4, PENALTY_SAVED: 0, PENALTY_MISSED: -2, OWN_GOAL: -2,
    MOTM: 3, EXTRA_TIME_BONUS: 1, INJURY_NO_SUB: -1,
  },
  MID: {
    GOAL: 5, ASSIST: 3, YELLOW_CARD: -2, RED_CARD: -3, SECOND_YELLOW: -3,
    CLEAN_SHEET: 1, PENALTY_SAVED: 0, PENALTY_MISSED: -2, OWN_GOAL: -2,
    MOTM: 3, EXTRA_TIME_BONUS: 1, INJURY_NO_SUB: -1,
  },
  FWD: {
    GOAL: 4, ASSIST: 3, YELLOW_CARD: -1, RED_CARD: -3, SECOND_YELLOW: -3,
    CLEAN_SHEET: 0, PENALTY_SAVED: 0, PENALTY_MISSED: -2, OWN_GOAL: -2,
    MOTM: 3, EXTRA_TIME_BONUS: 1, INJURY_NO_SUB: -1,
  },
};

export const APPEARANCE_POINTS = { PLAYED_60_PLUS: 2, PLAYED_UNDER_60: 1 };

// این تابع db رو lazy import می‌کنه تا در seed مشکل نداشته باشیم
export async function getPointsForEvent(position: Position, eventType: EventType): Promise<number> {
  const { db } = await import("@/lib/db");
  const rule = await db.scoringRule.findUnique({
    where: { position_eventType: { position, eventType } },
  });
  if (rule) return rule.points;
  return DEFAULT_RULES[position]?.[eventType] ?? 0;
}

export async function calculateMatchPoints(stat: {
  position: Position;
  goals: number;
  assists: number;
  yellowCards: number;
  redCards: number;
  minutesPlayed: number;
  cleanSheet: boolean;
  penaltySaved: number;
  penaltyMissed: number;
  ownGoals: number;
  isMotm: boolean;
  extraTimeBonus: number;
}): Promise<number> {
  let pts = 0;

  if (stat.minutesPlayed >= 60) pts += APPEARANCE_POINTS.PLAYED_60_PLUS;
  else if (stat.minutesPlayed > 0) pts += APPEARANCE_POINTS.PLAYED_UNDER_60;

  pts += stat.goals * (await getPointsForEvent(stat.position, "GOAL"));
  pts += stat.assists * (await getPointsForEvent(stat.position, "ASSIST"));
  pts += stat.yellowCards * (await getPointsForEvent(stat.position, "YELLOW_CARD"));
  pts += stat.redCards * (await getPointsForEvent(stat.position, "RED_CARD"));
  pts += stat.penaltySaved * (await getPointsForEvent(stat.position, "PENALTY_SAVED"));
  pts += stat.penaltyMissed * (await getPointsForEvent(stat.position, "PENALTY_MISSED"));
  pts += stat.ownGoals * (await getPointsForEvent(stat.position, "OWN_GOAL"));
  pts += stat.extraTimeBonus * (await getPointsForEvent(stat.position, "EXTRA_TIME_BONUS"));
  if (stat.cleanSheet) pts += await getPointsForEvent(stat.position, "CLEAN_SHEET");
  if (stat.isMotm) pts += await getPointsForEvent(stat.position, "MOTM");

  return pts;
}
