# utils/referral.py

import logging
from login_signup.models import User
from wallet.models import ShoppingPoint
from setting.views import *
from vendor_listing.tasks import send_referrer_reward_email, send_referred_reward_email

logger = logging.getLogger(__name__)

def apply_referral_rewards(buyer_user):
    try:
        if not buyer_user.referred_by_id or buyer_user.total_points > 0:
            logger.info("Referral conditions not met.")
            return

        referrer_points = int(get_setting_value('referrer_reward_points'))
        referred_points = int(get_setting_value('referred_user_reward_points'))

        referrer_user = buyer_user.referred_by

        # REFERRER POINTS
        try:
            referrer_point_exists = ShoppingPoint.objects.filter(
                user=referrer_user,
                source_user=buyer_user,
                transaction_type='credit'
            ).exists()

            if not referrer_point_exists:
                ShoppingPoint.objects.create(
                    user=referrer_user,
                    transaction_type='credit',
                    points=referrer_points,
                    description="Referral reward",
                    source_user=buyer_user
                )
                logger.info(f"[REFERRER] Created ShoppingPoint for referrer {referrer_user.id} with points : {referrer_user.total_points}")

                send_referrer_reward_email.delay(referrer_user.id, referrer_points, buyer_user.id)

                referrer_user.total_points = (referrer_user.total_points or 0) + referrer_points
                referrer_user.save()
                logger.info(
                    f"[REFERRER] Referrer {referrer_user.id} credited with {referrer_points} points. "
                    f"New total_points: {referrer_user.total_points}"
                )
            else:
                logger.info(f"Referrer reward already exists for {referrer_user} <- {buyer_user}")
        except Exception as e:
            logger.exception(f"Error awarding points to referrer {referrer_user.id}: {str(e)}")

        # REFERRED USER POINTS
        try:
            referred_point_exists = ShoppingPoint.objects.filter(
                user=buyer_user,
                source_user=referrer_user,
                transaction_type='credit'
            ).exists()

            if not referred_point_exists:
                ShoppingPoint.objects.create(
                    user=buyer_user,
                    transaction_type='credit',
                    points=referred_points,
                    description="Welcome reward via referral code",
                    source_user=referrer_user
                )
                logger.info(f"[REFERRED] Created ShoppingPoint for referred user {buyer_user.id} with points : {buyer_user.total_points}")

                send_referred_reward_email.delay(buyer_user.id, referred_points)

                buyer_user.total_points = (buyer_user.total_points or 0) + referred_points
                buyer_user.save()
                logger.info(
                    f"[REFERRED] Referred user {buyer_user.id} credited with {referred_points} points. "
                    f"New total_points: {buyer_user.total_points}"
                )
            else:
                logger.info(f"Referred reward already exists for {buyer_user}")
        except Exception as e:
            logger.exception(f"Error awarding points to referred user {buyer_user.id}: {str(e)}")

    except Exception as outer_exception:
        logger.exception(f"Unexpected error in apply_referral_rewards: {str(outer_exception)}")
