"""
Debug command to test token refresh activity tracking.

This command helps debug issues with token refresh not updating user activity.
"""

from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.test import Client
from rest_framework_simplejwt.tokens import RefreshToken
import json

User = get_user_model()


class Command(BaseCommand):
    help = 'Debug token refresh activity tracking'

    def add_arguments(self, parser):
        parser.add_argument(
            '--user-id',
            type=int,
            help='User ID to test with',
        )
        parser.add_argument(
            '--phone',
            type=str,
            help='User phone to test with',
        )
        parser.add_argument(
            '--clear-cache',
            action='store_true',
            help='Clear cache before testing',
        )

    def handle(self, *args, **options):
        self.stdout.write("=== Token Refresh Activity Tracking Debug ===\n")
        
        # Clear cache if requested
        if options['clear_cache']:
            cache.clear()
            self.stdout.write(self.style.SUCCESS("✓ Cache cleared"))
        
        # Get user
        user = None
        if options['user_id']:
            try:
                user = User.objects.get(id=options['user_id'])
            except User.DoesNotExist:
                self.stdout.write(self.style.ERROR(f"User with ID {options['user_id']} not found"))
                return
        elif options['phone']:
            try:
                user = User.objects.get(phone=options['phone'])
            except User.DoesNotExist:
                self.stdout.write(self.style.ERROR(f"User with phone {options['phone']} not found"))
                return
        else:
            # Use first user
            user = User.objects.first()
            if not user:
                self.stdout.write(self.style.ERROR("No users found in database"))
                return
        
        self.stdout.write(f"Testing with user: {user} (ID: {user.id})")
        self.stdout.write(f"Current last_active_date: {user.last_active_date}")
        
        # Generate refresh token
        refresh = RefreshToken.for_user(user)
        refresh_token = str(refresh)
        
        self.stdout.write(f"Generated refresh token: {refresh_token[:50]}...")
        
        # Test token refresh endpoint
        client = Client()
        refresh_data = {'refresh': refresh_token}
        
        self.stdout.write("\n--- Testing Token Refresh Endpoint ---")
        response = client.post(
            '/api/user/token/refresh/', 
            data=json.dumps(refresh_data),
            content_type='application/json'
        )
        
        self.stdout.write(f"Response status: {response.status_code}")
        self.stdout.write(f"Response headers: {dict(response.items())}")
        
        if response.status_code == 200:
            try:
                response_data = json.loads(response.content.decode())
                self.stdout.write(f"Response keys: {list(response_data.keys())}")
                
                if 'access' in response_data:
                    self.stdout.write(self.style.SUCCESS("✓ Access token returned"))
                else:
                    self.stdout.write(self.style.ERROR("✗ No access token in response"))
                
                if 'refresh' in response_data:
                    self.stdout.write(self.style.SUCCESS("✓ Refresh token returned"))
                else:
                    self.stdout.write(self.style.WARNING("⚠ No refresh token in response"))
                    
            except json.JSONDecodeError:
                self.stdout.write(self.style.ERROR("✗ Invalid JSON response"))
                self.stdout.write(f"Response content: {response.content.decode()}")
        else:
            self.stdout.write(self.style.ERROR(f"✗ Request failed: {response.content.decode()}"))
        
        # Check if activity was updated
        user.refresh_from_db()
        self.stdout.write(f"\nUser last_active_date after refresh: {user.last_active_date}")
        
        if user.last_active_date:
            self.stdout.write(self.style.SUCCESS("✓ User activity was updated"))
        else:
            self.stdout.write(self.style.ERROR("✗ User activity was NOT updated"))
        
        # Check cache status
        cache_key = f"user_activity_{user.pk}"
        cached_value = cache.get(cache_key)
        self.stdout.write(f"Cache value for user: {cached_value}")
        
        # Test middleware detection
        self.stdout.write("\n--- Testing Middleware Detection ---")
        from main.middleware import UserActivityMiddleware
        from django.test import RequestFactory
        
        factory = RequestFactory()
        middleware = UserActivityMiddleware(get_response=lambda r: r)
        
        # Create a POST request to the refresh endpoint
        request = factory.post('/api/user/token/refresh/')
        
        # Create a mock successful response
        class MockResponse:
            status_code = 200
            content = json.dumps({'access': 'test_token', 'refresh': 'test_refresh'}).encode()
        
        response = MockResponse()
        
        # Test middleware detection
        is_login = middleware._is_successful_login(request, response)
        self.stdout.write(f"Middleware detects refresh as login: {is_login}")
        
        if is_login:
            self.stdout.write(self.style.SUCCESS("✓ Middleware correctly detects refresh endpoint"))
        else:
            self.stdout.write(self.style.ERROR("✗ Middleware does not detect refresh endpoint"))
        
        # Test user extraction
        extracted_user = middleware._extract_user_from_login_response(request, response)
        self.stdout.write(f"Extracted user: {extracted_user}")
        
        self.stdout.write("\n=== Debug Complete ===") 