from rest_framework.response import Response 
from rest_framework.decorators import api_view
from .services import select_random_squad  , pick_squad,suggest_transfers,load_squad_using_manager_id
@api_view(['GET'])
def suggest_squad(request):
    team = select_random_squad()
    if team :
        return Response(team)
    return Response({'error': 'Could not generate a valid team with the given constraints.'}, status=500)
@api_view(['POST'])
def select_squad(request):
    team = request.data
    formation = pick_squad(team)
    return Response(formation)

@api_view(['POST'])
def suggest_transfer(request):
    data = request.data
    players_id = data.get('changes', [])
    budget = data.get('budget', 0)
    team = data.get('team', [])
    free_transfers = data.get('free', 0)
    transfers = suggest_transfers(players_id,team, budget, free_transfers)
    return Response(transfers)
@api_view(['GET'])
def load_from_id(request, id):
    """
    Load a squad from a given ID.
    """
    try:
        return Response(load_squad_using_manager_id(id))
    except Exception as e:
        return Response({"detail":"Not found."}, status=500)
