from datetime import datetime

from django.db.models import Sum
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView

from accounting.models import Account, Transaction
from accounting.serializers import TransactionSerializer


class AccountingReportView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        queryset = Transaction.objects.select_related('account', 'created_by').all()

        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')
        account_id = request.query_params.get('account_id')
        transaction_type = request.query_params.get('transaction_type')

        if start_date:
            try:
                start = datetime.strptime(start_date, '%Y-%m-%d').date()
            except ValueError:
                return Response(
                    {'detail': 'فرمت start_date باید YYYY-MM-DD باشد.'},
                    status=status.HTTP_400_BAD_REQUEST,
                )
            queryset = queryset.filter(transaction_date__gte=start)

        if end_date:
            try:
                end = datetime.strptime(end_date, '%Y-%m-%d').date()
            except ValueError:
                return Response(
                    {'detail': 'فرمت end_date باید YYYY-MM-DD باشد.'},
                    status=status.HTTP_400_BAD_REQUEST,
                )
            queryset = queryset.filter(transaction_date__lte=end)

        if account_id:
            try:
                account_id = int(account_id)
            except (TypeError, ValueError):
                return Response(
                    {'detail': 'account_id باید عدد صحیح باشد.'},
                    status=status.HTTP_400_BAD_REQUEST,
                )

            if not Account.objects.filter(id=account_id).exists():
                return Response(
                    {'detail': 'حساب موردنظر پیدا نشد.'},
                    status=status.HTTP_404_NOT_FOUND,
                )

            queryset = queryset.filter(account_id=account_id)

        if transaction_type:
            if transaction_type not in ('income', 'expense'):
                return Response(
                    {'detail': 'transaction_type باید income یا expense باشد.'},
                    status=status.HTTP_400_BAD_REQUEST,
                )
            queryset = queryset.filter(transaction_type=transaction_type)

        income = queryset.filter(transaction_type='income').aggregate(total=Sum('amount'))['total'] or 0
        expense = queryset.filter(transaction_type='expense').aggregate(total=Sum('amount'))['total'] or 0

        return Response({
            'total_income': income,
            'total_expense': expense,
            'net': income - expense,
            'transactions_count': queryset.count(),
            'items': TransactionSerializer(queryset, many=True).data,
        })
