"""Management command to cleanup expired user sessions.

This command removes expired user sessions from the database
to keep the session table clean and improve performance.
"""

from datetime import timedelta
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError

from apps.accounts.models import UserSession
from apps.accounts.utils import cleanup_expired_sessions


class Command(BaseCommand):
    """Management command to cleanup expired user sessions."""
    
    help = 'Cleanup expired user sessions from the database'
    
    def add_arguments(self, parser):
        """Add command arguments."""
        parser.add_argument(
            '--days',
            type=int,
            default=30,
            help='Remove sessions older than this many days (default: 30)'
        )
        
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be deleted without actually deleting'
        )
        
        parser.add_argument(
            '--force',
            action='store_true',
            help='Force cleanup without confirmation'
        )
        
        parser.add_argument(
            '--inactive-only',
            action='store_true',
            help='Only remove inactive sessions'
        )
    
    def handle(self, *args, **options):
        """Handle the command execution."""
        days = options['days']
        dry_run = options['dry_run']
        force = options['force']
        inactive_only = options['inactive_only']
        
        # Calculate cutoff date
        cutoff_date = timezone.now() - timedelta(days=days)
        
        # Build queryset
        queryset = UserSession.objects.filter(
            created_at__lt=cutoff_date
        )
        
        if inactive_only:
            queryset = queryset.filter(is_active=False)
        
        # Get count
        session_count = queryset.count()
        
        if session_count == 0:
            self.stdout.write(
                self.style.SUCCESS('No expired sessions found to cleanup.')
            )
            return
        
        # Show what will be deleted
        self.stdout.write(
            f'Found {session_count} sessions older than {days} days.'
        )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('DRY RUN: No sessions will be deleted.')
            )
            
            # Show sample sessions
            sample_sessions = queryset[:5]
            for session in sample_sessions:
                self.stdout.write(
                    f'  - Session for {session.user.username} '
                    f'from {session.ip_address} '
                    f'(created: {session.created_at})'
                )
            
            if session_count > 5:
                self.stdout.write(f'  ... and {session_count - 5} more sessions')
            
            return
        
        # Confirm deletion
        if not force:
            confirm = input(
                f'Are you sure you want to delete {session_count} sessions? '
                'This action cannot be undone. [y/N]: '
            )
            
            if confirm.lower() not in ['y', 'yes']:
                self.stdout.write(
                    self.style.WARNING('Operation cancelled.')
                )
                return
        
        # Perform cleanup
        try:
            if inactive_only:
                deleted_count = self._cleanup_inactive_sessions(cutoff_date)
            else:
                deleted_count = cleanup_expired_sessions(days)
            
            self.stdout.write(
                self.style.SUCCESS(
                    f'Successfully deleted {deleted_count} expired sessions.'
                )
            )
            
        except Exception as e:
            raise CommandError(f'Error during cleanup: {str(e)}')
    
    def _cleanup_inactive_sessions(self, cutoff_date):
        """Cleanup only inactive sessions.
        
        Args:
            cutoff_date: DateTime cutoff for session age
            
        Returns:
            Number of deleted sessions
        """
        queryset = UserSession.objects.filter(
            created_at__lt=cutoff_date,
            is_active=False
        )
        
        count = queryset.count()
        queryset.delete()
        
        return count