from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from clubs.models import Club
from clubs.season_planning import cashflow
from economy.models import Wallet
from .services import AccountingPeriodService,BudgetService
from .models import ClubBudget


class FinancialControlRoom(APIView):
    permission_classes=[permissions.IsAuthenticated]
    def get(self,request,club_id):
        club=get_object_or_404(Club,pk=club_id)
        if club.owner_id != request.user.pk:return Response({'detail':'Not club owner'},status=403)
        wallet=Wallet.objects.filter(club=club).first()
        period=AccountingPeriodService.current_for(club)
        budget=ClubBudget.objects.filter(club=club,period=period,status='ACTIVE').first() if period else None
        forecast=cashflow(club,days=365)
        from club_commercial.income_policy import outlook
        return Response({'club_id':str(club.pk),'available':str(wallet.available_balance if wallet else 0),
            'reserved':str(wallet.reserved_balance if wallet else 0),
            'backed_available':str(wallet.backed_available_balance if wallet else 0),
            'forecast':forecast,'income_outlook':outlook(club,cash_forecast=forecast),
            'budget':BudgetService.report(budget) if budget else None,
            'alerts':([{'code':'CASH_DEFICIT','date':forecast['first_cash_deficit']}] if forecast['first_cash_deficit'] else [])+
                     ([{'code':'NO_OPEN_PERIOD'}] if not period or period.is_closed else [])+
                     ([{'code':'NO_ACTIVE_BUDGET'}] if not budget else [])})
