from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone

from subscriptions.models import SeekerSubscription, SubscriptionPlan

User = get_user_model()


class Command(BaseCommand):
    help = 'Activate Professional Plus (K20) job alerts for a seeker'

    def add_arguments(self, parser):
        parser.add_argument('email', help='Seeker account email address')
        parser.add_argument(
            '--months',
            type=int,
            default=0,
            help='Subscription length in months (0 = no expiry)',
        )
        parser.add_argument(
            '--deactivate',
            action='store_true',
            help='Deactivate job alerts for this user',
        )

    def handle(self, *args, **options):
        email = options['email'].strip().lower()
        try:
            user = User.objects.get(email__iexact=email)
        except User.DoesNotExist as exc:
            raise CommandError(f'No user found with email: {email}') from exc

        if user.role != User.Role.SEEKER:
            raise CommandError(f'{email} is not a seeker account.')

        if options['deactivate']:
            updated = SeekerSubscription.objects.filter(user=user).update(is_active=False)
            from subscriptions.benefits import revoke_seeker_subscription_benefits
            revoke_seeker_subscription_benefits(user)
            if updated:
                self.stdout.write(self.style.SUCCESS(f'Deactivated job alerts for {email}.'))
            else:
                self.stdout.write(self.style.WARNING(f'No subscription found for {email}.'))
            return

        try:
            plan = SubscriptionPlan.objects.get(
                slug=settings.SEEKER_PLUS_PLAN_SLUG,
                is_active=True,
            )
        except SubscriptionPlan.DoesNotExist as exc:
            raise CommandError(
                f'Plan "{settings.SEEKER_PLUS_PLAN_SLUG}" not found. Run: python manage.py seed_plans'
            ) from exc

        expires_at = None
        months = options['months']
        if months > 0:
            expires_at = timezone.now() + timezone.timedelta(days=months * 30)

        subscription, created = SeekerSubscription.objects.update_or_create(
            user=user,
            defaults={
                'plan': plan,
                'is_active': True,
                'expires_at': expires_at,
            },
        )
        action = 'Activated' if created else 'Updated'
        expiry = expires_at.strftime('%Y-%m-%d') if expires_at else 'no expiry'
        self.stdout.write(
            self.style.SUCCESS(
                f'{action} Professional Plus job alerts for {email} (expires: {expiry}).'
            )
        )
