"""
API views for quota management.
"""

from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from .quota_service import QuotaService
from .models import QuotaOverage
from smoothschedule.identity.users.models import User


def is_owner_or_manager(user):
    """Check if user is a tenant owner or manager."""
    return user.role in [User.Role.TENANT_OWNER, User.Role.TENANT_MANAGER]


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def quota_status_view(request):
    """
    Get current quota status for the user's tenant.

    GET /api/quota/status/

    Returns:
        - active_overages: List of active quota overages
        - usage: Current usage for each quota type
    """
    user = request.user

    if not user.tenant:
        return Response(
            {'error': 'No tenant associated with this user'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not is_owner_or_manager(user):
        return Response(
            {'error': 'Only owners and managers can view quota status'},
            status=status.HTTP_403_FORBIDDEN
        )

    service = QuotaService(user.tenant)

    # Get active overages
    overages = service.get_active_overages()

    # Get current usage for all quota types
    usage = {}
    for quota_type, config in service.QUOTA_CONFIG.items():
        usage[quota_type] = {
            'current': service.get_current_usage(quota_type),
            'limit': service.get_limit(quota_type),
            'display_name': config['display_name'],
        }

    return Response({
        'active_overages': overages,
        'usage': usage,
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def quota_resources_view(request, quota_type):
    """
    Get list of resources that can be archived for a specific quota type.

    GET /api/quota/resources/<quota_type>/

    Returns list of resources with their details and whether they're archived.
    """
    user = request.user

    if not user.tenant:
        return Response(
            {'error': 'No tenant associated with this user'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not is_owner_or_manager(user):
        return Response(
            {'error': 'Only owners and managers can view quota resources'},
            status=status.HTTP_403_FORBIDDEN
        )

    resources = []

    if quota_type == 'MAX_ADDITIONAL_USERS':
        # Get users excluding owner
        users = User.objects.filter(
            tenant=user.tenant
        ).exclude(
            role=User.Role.TENANT_OWNER
        ).order_by('date_joined')

        for u in users:
            resources.append({
                'id': u.id,
                'name': u.get_full_name() or u.username,
                'email': u.email,
                'role': u.get_role_display(),
                'created_at': u.date_joined.isoformat(),
                'is_archived': u.is_archived_by_quota,
                'archived_at': u.archived_by_quota_at.isoformat() if u.archived_by_quota_at else None,
            })

    elif quota_type == 'MAX_RESOURCES':
        from smoothschedule.scheduling.schedule.models import Resource
        for r in Resource.objects.all().order_by('created_at'):
            resources.append({
                'id': r.id,
                'name': r.name,
                'type': r.get_type_display() if hasattr(r, 'get_type_display') else r.type,
                'created_at': r.created_at.isoformat() if hasattr(r, 'created_at') else None,
                'is_archived': r.is_archived_by_quota,
                'archived_at': r.archived_by_quota_at.isoformat() if r.archived_by_quota_at else None,
            })

    elif quota_type == 'MAX_SERVICES':
        from smoothschedule.scheduling.schedule.models import Service
        for s in Service.objects.all().order_by('created_at'):
            resources.append({
                'id': s.id,
                'name': s.name,
                'duration': s.duration,
                'price': str(s.price) if s.price else None,
                'created_at': s.created_at.isoformat() if hasattr(s, 'created_at') else None,
                'is_archived': s.is_archived_by_quota,
                'archived_at': s.archived_by_quota_at.isoformat() if s.archived_by_quota_at else None,
            })

    else:
        return Response(
            {'error': f'Unknown quota type: {quota_type}'},
            status=status.HTTP_400_BAD_REQUEST
        )

    return Response({
        'quota_type': quota_type,
        'resources': resources,
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def quota_archive_view(request):
    """
    Archive selected resources to resolve quota overage.

    POST /api/quota/archive/

    Body:
        - quota_type: The quota type (e.g., 'MAX_ADDITIONAL_USERS')
        - resource_ids: List of resource IDs to archive
    """
    user = request.user

    if not user.tenant:
        return Response(
            {'error': 'No tenant associated with this user'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not is_owner_or_manager(user):
        return Response(
            {'error': 'Only owners and managers can archive resources'},
            status=status.HTTP_403_FORBIDDEN
        )

    quota_type = request.data.get('quota_type')
    resource_ids = request.data.get('resource_ids', [])

    if not quota_type:
        return Response(
            {'error': 'quota_type is required'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not resource_ids:
        return Response(
            {'error': 'resource_ids is required'},
            status=status.HTTP_400_BAD_REQUEST
        )

    service = QuotaService(user.tenant)

    # Verify quota type is valid
    if quota_type not in service.QUOTA_CONFIG:
        return Response(
            {'error': f'Unknown quota type: {quota_type}'},
            status=status.HTTP_400_BAD_REQUEST
        )

    # Archive the resources
    archived_count = service.archive_resources(quota_type, resource_ids)

    # Check if overage is now resolved
    current_usage = service.get_current_usage(quota_type)
    limit = service.get_limit(quota_type)
    is_resolved = current_usage <= limit

    return Response({
        'archived_count': archived_count,
        'current_usage': current_usage,
        'limit': limit,
        'is_resolved': is_resolved,
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def quota_unarchive_view(request):
    """
    Unarchive a resource (only if there's room in the quota).

    POST /api/quota/unarchive/

    Body:
        - quota_type: The quota type
        - resource_id: The resource ID to unarchive
    """
    user = request.user

    if not user.tenant:
        return Response(
            {'error': 'No tenant associated with this user'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not is_owner_or_manager(user):
        return Response(
            {'error': 'Only owners and managers can unarchive resources'},
            status=status.HTTP_403_FORBIDDEN
        )

    quota_type = request.data.get('quota_type')
    resource_id = request.data.get('resource_id')

    if not quota_type or not resource_id:
        return Response(
            {'error': 'quota_type and resource_id are required'},
            status=status.HTTP_400_BAD_REQUEST
        )

    service = QuotaService(user.tenant)

    # Try to unarchive
    success = service.unarchive_resource(quota_type, resource_id)

    if not success:
        return Response(
            {'error': 'Cannot unarchive: quota limit would be exceeded'},
            status=status.HTTP_400_BAD_REQUEST
        )

    return Response({
        'success': True,
        'resource_id': resource_id,
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def quota_overage_detail_view(request, overage_id):
    """
    Get details for a specific quota overage.

    GET /api/quota/overages/<overage_id>/
    """
    user = request.user

    if not user.tenant:
        return Response(
            {'error': 'No tenant associated with this user'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not is_owner_or_manager(user):
        return Response(
            {'error': 'Only owners and managers can view overage details'},
            status=status.HTTP_403_FORBIDDEN
        )

    try:
        overage = QuotaOverage.objects.get(
            id=overage_id,
            tenant=user.tenant
        )
    except QuotaOverage.DoesNotExist:
        return Response(
            {'error': 'Overage not found'},
            status=status.HTTP_404_NOT_FOUND
        )

    service = QuotaService(user.tenant)
    config = service.QUOTA_CONFIG.get(overage.quota_type, {})

    return Response({
        'id': overage.id,
        'quota_type': overage.quota_type,
        'display_name': config.get('display_name', overage.quota_type),
        'status': overage.status,
        'current_usage': overage.current_usage,
        'allowed_limit': overage.allowed_limit,
        'overage_amount': overage.overage_amount,
        'days_remaining': overage.days_remaining,
        'grace_period_ends_at': overage.grace_period_ends_at.isoformat() if overage.grace_period_ends_at else None,
        'created_at': overage.created_at.isoformat(),
        'initial_email_sent_at': overage.initial_email_sent_at.isoformat() if overage.initial_email_sent_at else None,
        'week_reminder_sent_at': overage.week_reminder_sent_at.isoformat() if overage.week_reminder_sent_at else None,
        'day_reminder_sent_at': overage.day_reminder_sent_at.isoformat() if overage.day_reminder_sent_at else None,
        'archived_resource_ids': overage.archived_resource_ids,
    })
