"""
Simple CAS views - bare minimum implementation.
"""

from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
from django.http import HttpResponse
from django.views import View
import urllib.parse


class SimpleCASLoginView(View):
    """Simple CAS login view."""
    
    def get(self, request):
        ticket = request.GET.get('ticket')
        
        if ticket:
            # Coming back from CAS with ticket - validate it
            service_url = request.build_absolute_uri().split('?')[0]  # Remove query params
            
            user = authenticate(request=request, ticket=ticket, service=service_url)
            
            if user:
                login(request, user)
                return redirect(settings.LOGIN_REDIRECT_URL)
            else:
                return HttpResponse("Authentication failed", status=401)
        
        else:
            # No ticket - redirect to CAS
            service_url = request.build_absolute_uri().split('?')[0]  # Remove query params
            cas_login_url = f"{settings.CAS_SERVER_URL.rstrip('/')}/login?service={urllib.parse.quote(service_url)}"
            return redirect(cas_login_url)


class SimpleCASLogoutView(View):
    """Simple CAS logout view."""
    
    def get(self, request):
        logout(request)
        
        # Redirect to CAS logout
        cas_logout_url = f"{settings.CAS_SERVER_URL.rstrip('/')}/logout"
        return redirect(cas_logout_url)
