from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import Vote


@require_POST
def vote(request):
    """Handle voting for blog posts, tools, and other content"""
    content_type = request.POST.get('content_type')
    content_id = request.POST.get('content_id')
    
    if not content_type or not content_id:
        return JsonResponse({'error': 'Missing content_type or content_id'}, status=400)
    
    # Ensure session is created
    if not request.session.session_key:
        request.session.create()
    
    session_key = request.session.session_key
    
    # Get or create the vote record
    vote_obj, created = Vote.objects.get_or_create(
        content_type=content_type,
        content_id=content_id,
        defaults={'vote_count': 0, 'voted_sessions': []}
    )
    
    # Check if user has already voted
    if session_key in vote_obj.voted_sessions:
        return JsonResponse({
            'success': False,
            'message': 'You have already voted',
            'vote_count': vote_obj.vote_count,
            'has_voted': True
        })
    
    # Add vote
    vote_obj.vote_count += 1
    vote_obj.voted_sessions.append(session_key)
    vote_obj.save()
    
    return JsonResponse({
        'success': True,
        'vote_count': vote_obj.vote_count,
        'has_voted': True
    })


def get_vote_count(request, content_type, content_id):
    """Get vote count for a specific item"""
    try:
        vote = Vote.objects.get(content_type=content_type, content_id=content_id)
        has_voted = request.session.session_key in vote.voted_sessions if request.session.session_key else False
        return JsonResponse({
            'vote_count': vote.vote_count,
            'has_voted': has_voted
        })
    except Vote.DoesNotExist:
        return JsonResponse({
            'vote_count': 0,
            'has_voted': False
        })


def get_vote_data(request, content_type, content_id):
    """Helper function to get vote data for templates (not a view)"""
    try:
        vote = Vote.objects.get(content_type=content_type, content_id=content_id)
        has_voted = request.session.session_key in vote.voted_sessions if request.session.session_key else False
        return {
            'vote_count': vote.vote_count,
            'has_voted': has_voted
        }
    except Vote.DoesNotExist:
        return {
            'vote_count': 0,
            'has_voted': False
        }
