"""Match lineup and formation orchestration.

The lineup domain deliberately lives next to Match because it is match-specific
configuration rather than persistent club roster state.  Current squad
membership remains owned by Clubs; this service only selects from that
membership for a particular Match.

Locking policy:
    Match -> MatchLineup(s) -> ClubSquadMembership(s)

MatchLifecycleService already locks Competition -> Match before calling the
internal lock_for_match_start() hook, so the start path extends that canonical
order with the lineup rows and roster rows.
"""

from collections.abc import Iterable, Mapping
import uuid

from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import IntegrityError, transaction
from django.utils import timezone

from clubs.models import ClubSquadMembership
from leagues.constants import LeagueCompetitionType
from players.models import Player, Position

from .constants import (
    FORMATION_SLOTS,
    FormationCode,
    LineupEntryRole,
    TacticalPlayerRole,
    LineupStatus,
    MatchStatus,
)
from .exceptions import (
    DuplicateLineupPlayerError,
    IncompleteLineupError,
    InvalidCaptainError,
    InvalidFormationError,
    InvalidLineupClubError,
    InvalidLineupPlayerError,
    InvalidLineupSlotError,
    InvalidLineupRoleError,
    LineupNotEditableError,
    LineupValidationError,
    LineupNotFoundError,
    LineupNotReopenableError,
    LineupNotSubmittableError,
    MatchLineupsNotReadyError,
    MedicallyUnavailableLineupPlayerError,
)
from .models import Match, MatchLineup, MatchLineupEntry
from .engine.roles import resolve_tactical_role


class MatchLineupService:
    """Authoritative mutation service for match-specific team selection."""

    EDITABLE_MATCH_STATUSES = {MatchStatus.PENDING, MatchStatus.SCHEDULED}

    @staticmethod
    @transaction.atomic
    def save_draft(
        *,
        match_id,
        club_id,
        formation,
        starters,
        substitutes=(),
        captain_id=None,
        youth_team_id=None,
        tactical_plan=None,
    ):
        match = MatchLineupService._lock_match(match_id)
        club_id = _normalize_uuid(club_id, field_name="club_id")
        MatchLineupService._ensure_match_editable(match)
        participant_type, resolved_youth_team_id = MatchLineupService._resolve_fixture_participant(
            match=match, club_id=club_id, youth_team_id=youth_team_id
        )

        formation = _validate_formation(formation)
        starter_rows = _normalize_starters(starters)
        substitute_ids = _normalize_player_ids(substitutes, field_name="substitutes")
        captain_id = (
            _normalize_uuid(captain_id, field_name="captain_id")
            if captain_id is not None
            else None
        )

        selected_player_ids = [row["player_id"] for row in starter_rows] + substitute_ids
        _ensure_unique_player_ids(selected_player_ids)
        _validate_slots_for_draft(formation=formation, starter_rows=starter_rows)
        _validate_captain_for_draft(
            captain_id=captain_id,
            starter_rows=starter_rows,
        )

        lineup = (
            MatchLineup.objects.select_for_update()
            .filter(match=match, club_id=club_id)
            .first()
        )
        if lineup is None:
            lineup = MatchLineup.objects.create(
                match=match,
                club_id=club_id,
                participant_type=participant_type,
                youth_team_id=resolved_youth_team_id,
                formation=formation,
                status=LineupStatus.DRAFT,
            )
        elif (
            lineup.participant_type != participant_type
            or lineup.youth_team_id != resolved_youth_team_id
        ):
            raise InvalidLineupClubError(
                "Existing lineup participant identity does not match the fixture."
            )
        elif lineup.status != LineupStatus.DRAFT:
            raise LineupNotEditableError(
                "Only a DRAFT lineup can be edited. Reopen a submitted lineup first."
            )

        # Canonical mutation lock order is Match -> Lineup -> Roster. Keep
        # roster validation after the lineup row lock so concurrent edit/submit
        # requests cannot deadlock on inverse locks under PostgreSQL.
        players_by_id = MatchLineupService._validate_current_roster(
            match=match,
            club_id=club_id,
            participant_type=participant_type,
            youth_team_id=resolved_youth_team_id,
            player_ids=selected_player_ids,
            lock_rows=True,
        )
        _validate_required_position_compatibility(
            starter_rows=starter_rows,
            players_by_id=players_by_id,
        )

        lineup.formation = formation
        lineup.save(update_fields=["formation", "updated_at"])
        lineup.entries.all().delete()

        entries = []
        for row in starter_rows:
            entries.append(
                MatchLineupEntry(
                    lineup=lineup,
                    player_id=row["player_id"],
                    role=LineupEntryRole.STARTER,
                    tactical_role=row["tactical_role"],
                    slot=row["slot"],
                    is_captain=(row["player_id"] == captain_id),
                )
            )
        for player_id in substitute_ids:
            entries.append(
                MatchLineupEntry(
                    lineup=lineup,
                    player_id=player_id,
                    role=LineupEntryRole.SUBSTITUTE,
                    tactical_role=TacticalPlayerRole.AUTO,
                    slot="",
                    is_captain=False,
                )
            )

        try:
            with transaction.atomic():
                MatchLineupEntry.objects.bulk_create(entries)
        except IntegrityError as exc:
            raise InvalidLineupPlayerError(
                "Lineup entries violate a database integrity rule."
            ) from exc

        if tactical_plan is not None:
            from .tactical_catalog import apply_plan
            apply_plan(lineup, tactical_plan)
        return MatchLineupService._load_lineup(lineup.pk)

    @staticmethod
    @transaction.atomic
    def submit(*, lineup_id):
        match, lineup = MatchLineupService._lock_match_then_lineup(lineup_id)
        MatchLineupService._ensure_match_editable(match)

        if lineup.status == LineupStatus.SUBMITTED:
            MatchLineupService._validate_complete_lineup(lineup, lock_roster=True)
            return MatchLineupService._load_lineup(lineup.pk)
        if lineup.status != LineupStatus.DRAFT:
            raise LineupNotSubmittableError(
                "Only a DRAFT lineup can be submitted."
            )

        MatchLineupService._validate_complete_lineup(lineup, lock_roster=True)
        lineup.status = LineupStatus.SUBMITTED
        lineup.submitted_at = timezone.now()
        lineup.locked_at = None
        lineup.save(
            update_fields=["status", "submitted_at", "locked_at", "updated_at"]
        )
        return MatchLineupService._load_lineup(lineup.pk)

    @staticmethod
    @transaction.atomic
    def reopen(*, lineup_id):
        match, lineup = MatchLineupService._lock_match_then_lineup(lineup_id)
        if lineup.status != LineupStatus.SUBMITTED:
            raise LineupNotReopenableError(
                "Only a SUBMITTED lineup can be reopened before match start."
            )

        MatchLineupService._ensure_match_editable(match)

        lineup.status = LineupStatus.DRAFT
        lineup.submitted_at = None
        lineup.locked_at = None
        lineup.save(
            update_fields=["status", "submitted_at", "locked_at", "updated_at"]
        )
        return MatchLineupService._load_lineup(lineup.pk)

    @staticmethod
    def lock_submitted_at_deadline(*, match, locked_at=None):
        """Freeze every valid submitted lineup at the authoritative deadline.

        Missing/DRAFT/invalid lineups are deliberately not auto-repaired. Their
        state is returned to MatchdayOperationsService, which records readiness
        evidence and blocks kickoff until an operator/team resolves the issue.
        """
        locked_at = locked_at or timezone.now()
        expected_clubs = [match.fixture.home_club_id, match.fixture.away_club_id]
        lineups = {
            lineup.club_id: lineup
            for lineup in MatchLineup.objects.select_for_update()
            .filter(match_id=match.pk)
            .order_by("club_id")
        }
        results = []
        for club_id in expected_clubs:
            lineup = lineups.get(club_id)
            if lineup is None:
                # A manager's persistent club XI (or the automatic 4-3-3
                # suggestion) is used *only* when this match has no lineup.
                # A DRAFT lineup is a deliberate match-specific override.
                from .default_lineups import DefaultLineupService
                try:
                    # Isolate each club's fallback so a failed eligibility
                    # check never leaves a half-created DRAFT behind.
                    with transaction.atomic():
                        lineup = DefaultLineupService.materialize_for_match(
                            match=match, club_id=club_id, at=locked_at
                        )
                except LineupValidationError:
                    results.append({"club_id": str(club_id), "result": "DEFAULT_INVALID"})
                    continue
                if lineup is None:
                    results.append({"club_id": str(club_id), "result": "MISSING"})
                    continue
                # It is now SUBMITTED; the normal locking path below still
                # revalidates it and freezes it as the historical match XI.
            if lineup.status == LineupStatus.LOCKED:
                results.append({"club_id": str(club_id), "result": "ALREADY_LOCKED"})
                continue
            if lineup.status != LineupStatus.SUBMITTED:
                results.append({"club_id": str(club_id), "result": lineup.status})
                continue
            try:
                MatchLineupService._validate_complete_lineup(lineup, lock_roster=True)
            except LineupValidationError:
                results.append({"club_id": str(club_id), "result": "INVALID"})
                continue
            lineup.status = LineupStatus.LOCKED
            lineup.locked_at = locked_at
            lineup.save(update_fields=["status", "locked_at", "updated_at"])
            results.append({"club_id": str(club_id), "result": "LOCKED"})
        return results

    @staticmethod
    def lock_for_match_start(*, match):
        """Validate and lock both lineups inside MatchLifecycleService.start().

        The caller must already hold the Match row lock.  The method locks both
        MatchLineup rows in deterministic club order, revalidates current roster
        membership, then turns both immutable for historical match execution.
        """

        expected_clubs = {match.fixture.home_club_id, match.fixture.away_club_id}
        # Legacy fixtures without a matchday deadline also receive the same
        # default only if no per-match selection was ever created.  Standard
        # matchday fixtures already materialize at their lineup deadline.
        from .default_lineups import DefaultLineupService
        for missing_club_id in sorted(expected_clubs, key=str):
            if not MatchLineup.objects.filter(match_id=match.pk, club_id=missing_club_id).exists():
                try:
                    with transaction.atomic():
                        DefaultLineupService.materialize_for_match(
                            match=match, club_id=missing_club_id
                        )
                except LineupValidationError:
                    # Preserve the original explicit readiness error below.
                    pass
        lineups = list(
            MatchLineup.objects.select_for_update()
            .filter(match_id=match.pk)
            .order_by("club_id")
        )
        if len(lineups) != 2 or {lineup.club_id for lineup in lineups} != expected_clubs:
            raise MatchLineupsNotReadyError(
                "Both fixture participants must have a submitted lineup before match start."
            )
        expected_youth = {
            match.fixture.home_club_id: match.fixture.home_youth_team_id,
            match.fixture.away_club_id: match.fixture.away_youth_team_id,
        }
        for lineup in lineups:
            if lineup.participant_type != match.fixture.competition_type:
                raise MatchLineupsNotReadyError(
                    "Lineup participant type no longer matches the fixture."
                )
            if lineup.youth_team_id != expected_youth[lineup.club_id]:
                raise MatchLineupsNotReadyError(
                    "Lineup youth-team identity no longer matches the fixture."
                )

        # Kickoff state must not be assembled while a concurrent Contract or
        # Transfer mutates one of the selected Players.  Lock all selected
        # Player rows in deterministic order *before* the late roster locks.
        # This preserves Player -> Roster ordering used by contract/transfer
        # workflows and avoids a Roster -> Player inversion.
        selected_player_ids = list(
            MatchLineupEntry.objects.filter(lineup__in=lineups)
            .values_list("player_id", flat=True)
            .distinct()
        )
        list(
            Player.objects.select_for_update()
            .filter(pk__in=selected_player_ids)
            .order_by("pk")
            .values_list("pk", flat=True)
        )

        now = timezone.now()
        for lineup in lineups:
            if lineup.status not in {LineupStatus.SUBMITTED, LineupStatus.LOCKED}:
                raise MatchLineupsNotReadyError(
                    "Both lineups must be SUBMITTED or deadline-LOCKED before match start."
                )
            try:
                MatchLineupService._validate_complete_lineup(
                    lineup,
                    lock_roster=True,
                )
            except LineupValidationError as exc:
                raise MatchLineupsNotReadyError(
                    "A submitted/locked lineup is no longer valid for match start."
                ) from exc

        for lineup in lineups:
            if lineup.status == LineupStatus.SUBMITTED:
                lineup.status = LineupStatus.LOCKED
                lineup.locked_at = now
                lineup.save(update_fields=["status", "locked_at", "updated_at"])

        return lineups

    @staticmethod
    def _validate_complete_lineup(lineup, *, lock_roster):
        entries = list(
            MatchLineupEntry.objects.filter(lineup=lineup)
            .select_related("player")
            .order_by("role", "slot", "player_id")
        )
        starters = [entry for entry in entries if entry.role == LineupEntryRole.STARTER]
        substitutes = [
            entry for entry in entries if entry.role == LineupEntryRole.SUBSTITUTE
        ]

        if len(starters) != 11:
            raise IncompleteLineupError(
                "A submitted lineup must contain exactly 11 starters."
            )

        expected_slots = set(FORMATION_SLOTS[lineup.formation])
        actual_slots = {entry.slot for entry in starters}
        if (lineup.formation == FormationCode.CUSTOM and (len(actual_slots) != 11 or "GK" not in actual_slots or not actual_slots <= expected_slots)) or (lineup.formation != FormationCode.CUSTOM and actual_slots != expected_slots):
            raise IncompleteLineupError(
                "Starter slots must exactly match the selected formation."
            )

        captains = [entry for entry in starters if entry.is_captain]
        if len(captains) != 1:
            raise InvalidCaptainError(
                "A submitted lineup must have exactly one starting captain."
            )
        if any(entry.is_captain for entry in substitutes):
            raise InvalidCaptainError("A substitute cannot be the captain.")

        player_ids = [str(entry.player_id) for entry in entries]
        _ensure_unique_player_ids(player_ids)
        players_by_id = MatchLineupService._validate_current_roster(
            match=lineup.match,
            club_id=lineup.club_id,
            participant_type=lineup.participant_type,
            youth_team_id=lineup.youth_team_id,
            player_ids=player_ids,
            lock_rows=lock_roster,
        )
        starter_rows = [
            {
                "player_id": str(entry.player_id),
                "slot": entry.slot,
                "tactical_role": entry.tactical_role,
            }
            for entry in starters
        ]
        _validate_slots_for_draft(formation=lineup.formation, starter_rows=starter_rows)
        _validate_required_position_compatibility(
            starter_rows=starter_rows,
            players_by_id=players_by_id,
        )
        _validate_medical_match_availability(players_by_id=players_by_id)
        if sum(p.position == "GK" for p in players_by_id.values()) < 2:
            raise InvalidLineupPlayerError("Matchday squad requires at least two goalkeepers.")
        from .set_piece_plans import MatchSetPiecePlanService
        MatchSetPiecePlanService.validate_for_lineup(lineup)

    @staticmethod
    def _validate_current_roster(
        *, match, club_id, participant_type, youth_team_id, player_ids, lock_rows
    ):
        if not player_ids:
            return {}
        if participant_type == LeagueCompetitionType.ADULT:
            queryset = ClubSquadMembership.objects.filter(
                club_id=club_id,
                player_id__in=player_ids,
            )
        elif participant_type == LeagueCompetitionType.YOUTH:
            if youth_team_id is None:
                raise InvalidLineupPlayerError(
                    "Youth lineup is missing its youth-team identity."
                )
            from academy.models import YouthSquadMembership

            queryset = YouthSquadMembership.objects.filter(
                youth_team_id=youth_team_id,
                youth_team__academy__club_id=club_id,
                player_id__in=player_ids,
            )
        else:
            raise InvalidLineupPlayerError("Unsupported lineup participant type.")

        if lock_rows:
            queryset = queryset.select_for_update()
        membership_player_ids = list(
            queryset.order_by("player_id").values_list("player_id", flat=True)
        )
        membership_keys = {str(player_id) for player_id in membership_player_ids}
        missing = [player_id for player_id in player_ids if player_id not in membership_keys]
        if missing:
            raise InvalidLineupPlayerError(
                "Every selected player must belong to the participant's current roster."
            )

        players = Player.objects.filter(pk__in=membership_player_ids)
        by_id = {str(player.pk): player for player in players}
        if len(by_id) != len(membership_keys):
            raise InvalidLineupPlayerError(
                "A selected squad player no longer exists."
            )

        # Competition registration is a second eligibility boundary beyond the
        # club's current roster.  A player may hold a valid contract and squad
        # membership but still be unavailable for this specific competition if
        # they were not named in the approved registration snapshot.
        try:
            from competition_registration.exceptions import CompetitionRegistrationError
            from competition_registration.services import CompetitionEligibilityService

            CompetitionEligibilityService.assert_match_players_registered(
                match=match,
                club_id=club_id,
                youth_team_id=youth_team_id,
                player_ids=player_ids,
            )
        except CompetitionRegistrationError as exc:
            raise InvalidLineupPlayerError(str(exc)) from exc

        return by_id

    @staticmethod
    def _ensure_match_editable(match):
        if match.status not in MatchLineupService.EDITABLE_MATCH_STATUSES:
            raise LineupNotEditableError(
                "Lineups can only be edited before the match starts."
            )
        # Calendar-scheduled production matches own a MatchdayOperation. Once
        # its deadline is reached, save/submit/reopen cannot bypass the lock.
        from .matchday import MatchdayOperationsService
        MatchdayOperationsService.assert_lineup_editable(match=match)

    @staticmethod
    def _resolve_fixture_participant(*, match, club_id, youth_team_id):
        fixture = match.fixture
        fixture_clubs = {str(fixture.home_club_id), str(fixture.away_club_id)}
        if str(club_id) not in fixture_clubs:
            raise InvalidLineupClubError(
                "The lineup club must be the fixture home or away club."
            )

        if fixture.competition_type == LeagueCompetitionType.ADULT:
            if youth_team_id is not None:
                raise InvalidLineupClubError(
                    "An ADULT fixture cannot receive a youth-team lineup."
                )
            return LeagueCompetitionType.ADULT, None

        if fixture.competition_type != LeagueCompetitionType.YOUTH:
            raise InvalidLineupClubError("Unsupported fixture participant type.")

        expected = (
            fixture.home_youth_team_id
            if str(club_id) == str(fixture.home_club_id)
            else fixture.away_youth_team_id
        )
        if expected is None:
            raise InvalidLineupClubError(
                "Youth fixture is missing its youth-team participant identity."
            )
        if youth_team_id is None or str(youth_team_id) != str(expected):
            raise InvalidLineupClubError(
                "Youth lineup must identify the exact youth team in the fixture."
            )
        return LeagueCompetitionType.YOUTH, expected

    @staticmethod
    def _lock_match(match_id):
        try:
            return (
                Match.objects.select_for_update(of=("self",))
                .select_related(
                    "fixture",
                    "fixture__competition",
                    "fixture__competition__season",
                    "fixture__federation_competition",
                    "fixture__federation_competition__season",
                    "fixture__home_youth_team",
                    "fixture__away_youth_team",
                )
                .get(pk=match_id)
            )
        except (Match.DoesNotExist, TypeError, ValueError, DjangoValidationError) as exc:
            from .exceptions import MatchNotFoundError

            raise MatchNotFoundError("Match does not exist.") from exc


    @staticmethod
    def _lock_match_then_lineup(lineup_id):
        try:
            match_id = MatchLineup.objects.values_list(
                "match_id", flat=True
            ).get(pk=lineup_id)
        except (
            MatchLineup.DoesNotExist,
            TypeError,
            ValueError,
            DjangoValidationError,
        ) as exc:
            raise LineupNotFoundError("Lineup does not exist.") from exc

        match = MatchLineupService._lock_match(match_id)
        lineup = MatchLineupService._lock_lineup(lineup_id)
        if lineup.match_id != match.pk:
            raise LineupNotFoundError("Lineup match identity changed during locking.")
        return match, lineup

    @staticmethod
    def _lock_lineup(lineup_id):
        try:
            return (
                MatchLineup.objects.select_for_update()
                .select_related("match", "club")
                .get(pk=lineup_id)
            )
        except (
            MatchLineup.DoesNotExist,
            TypeError,
            ValueError,
            DjangoValidationError,
        ) as exc:
            raise LineupNotFoundError("Lineup does not exist.") from exc

    @staticmethod
    def _load_lineup(lineup_id):
        return (
            MatchLineup.objects.select_related("match", "club", "youth_team")
            .prefetch_related("entries__player")
            .get(pk=lineup_id)
        )


def _normalize_uuid(value, *, field_name):
    try:
        return str(uuid.UUID(str(value)))
    except (TypeError, ValueError, AttributeError) as exc:
        raise InvalidLineupPlayerError(
            f"{field_name} must be a valid UUID."
        ) from exc


def _validate_formation(value):
    if value not in FormationCode.values:
        raise InvalidFormationError("Unsupported formation.")
    return value


def _normalize_starters(starters):
    if starters is None or isinstance(starters, (str, bytes)):
        raise InvalidLineupPlayerError("starters must be an iterable of mappings.")
    if not isinstance(starters, Iterable):
        raise InvalidLineupPlayerError("starters must be iterable.")

    rows = []
    for item in starters:
        if not isinstance(item, Mapping):
            raise InvalidLineupPlayerError(
                "Each starter must provide player_id and slot."
            )
        player_id = item.get("player_id")
        slot = item.get("slot")
        if player_id is None:
            raise InvalidLineupPlayerError("starter player_id is required.")
        if not isinstance(slot, str) or not slot.strip():
            raise InvalidLineupSlotError("starter slot is required.")
        normalized_slot = slot.strip().upper()
        tactical_role = item.get("tactical_role", TacticalPlayerRole.AUTO)
        if not isinstance(tactical_role, str) or not tactical_role.strip():
            raise InvalidLineupRoleError("starter tactical_role must be a non-empty string when supplied.")
        rows.append({
            "player_id": _normalize_uuid(player_id, field_name="starter player_id"),
            "slot": normalized_slot,
            "tactical_role": tactical_role.strip().upper(),
        })
    return rows


def _normalize_player_ids(values, *, field_name):
    if values is None:
        return []
    if isinstance(values, (str, bytes)) or not isinstance(values, Iterable):
        raise InvalidLineupPlayerError(f"{field_name} must be an iterable of player ids.")
    result = []
    for value in values:
        if value is None:
            raise InvalidLineupPlayerError(f"{field_name} cannot contain an empty player id.")
        result.append(_normalize_uuid(value, field_name=f"{field_name} player id"))
    return result


def _ensure_unique_player_ids(player_ids):
    if len(player_ids) != len(set(player_ids)):
        raise DuplicateLineupPlayerError(
            "A player cannot be selected twice in the same lineup."
        )


def _validate_slots_for_draft(*, formation, starter_rows):
    allowed = set(FORMATION_SLOTS[formation])
    slots = [row["slot"] for row in starter_rows]
    invalid = [slot for slot in slots if slot not in allowed]
    if invalid:
        raise InvalidLineupSlotError(
            "A starter slot does not belong to the selected formation."
        )
    if len(slots) != len(set(slots)):
        raise InvalidLineupSlotError(
            "A formation slot cannot contain more than one starter."
        )
    for row in starter_rows:
        try:
            resolve_tactical_role(row.get("tactical_role"), row["slot"])
        except ValueError as exc:
            raise InvalidLineupRoleError(str(exc)) from exc


def _validate_captain_for_draft(*, captain_id, starter_rows):
    if captain_id is None:
        return
    starter_ids = {row["player_id"] for row in starter_rows}
    if captain_id not in starter_ids:
        raise InvalidCaptainError("Captain must be one of the starting players.")


def _validate_required_position_compatibility(*, starter_rows, players_by_id):
    """Enforce only the non-negotiable goalkeeper compatibility rule.

    The source documentation requires position compatibility "where required"
    but does not define a complete out-of-position matrix.  The foundation
    therefore enforces the goalkeeper boundary and preserves tactical slot data
    for the later simulation layer to score more nuanced compatibility.
    """

    for row in starter_rows:
        player = players_by_id[row["player_id"]]
        if row["slot"] == "GK" and player.position != Position.GK:
            raise InvalidLineupPlayerError(
                "The GK formation slot requires a goalkeeper."
            )
        if row["slot"] != "GK" and player.position == Position.GK:
            raise InvalidLineupPlayerError(
                "A goalkeeper cannot occupy an outfield starting slot."
            )


def _validate_medical_match_availability(*, players_by_id):
    # InjuryService mutations acquire the Player row lock first. At match start
    # selected Player rows are already locked before this check, so an injury
    # cannot interleave between medical validation and kickoff snapshot. During
    # submit this is an optimistic check; kickoff revalidation remains final.
    from injuries.resolver import InjuryResolver

    unavailable = []
    for player_id, player in players_by_id.items():
        if not InjuryResolver.for_player(player=player).match_eligible:
            unavailable.append(player_id)
    if unavailable:
        raise MedicallyUnavailableLineupPlayerError(
            "A selected player has an active injury that makes them unavailable for the match."
        )
