import logging
from django.core.management.base import BaseCommand
from apps.subscriptions.models import Subscription,Payment,Plan
from apps.accounts.models import User
from apps.subscriptions.utils import UpgradeSubscription
from django.conf import settings


logger = logging.getLogger(__file__)
class Command(BaseCommand):
    help = "Sync data between PayPal and the database"

    def handle(self, *args, **options):
        users = User.objects.filter(is_active=True)

        for user in users:
            try:
                sub = Subscription.objects.get(user=user)
                try:
                    payment = Payment.objects.get(subscription=sub, is_active=True)
                    paypal_api = UpgradeSubscription(CLIENT_ID=settings.PAYPAL_CLIENTID, CLIENT_SECRET=settings.PAYPAL_SECRETID)
                    sub_detail = paypal_api.get_subscription_details(payment.sub_id).json()['status']

                    if sub_detail != "ACTIVE":
                        payment.is_active = False
                        payment.save()
                        logger.info(f"Payment {payment} for user {user} marked as inactive due to subscription status")

                except Payment.DoesNotExist:
                    logger.warning(f"No active payment found for user {user}")
                    continue

            except Subscription.DoesNotExist:
                logger.warning(f"No subscription found for user {user}")
                continue






