from django.conf import settings
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

from shortener.models import UrlData
from utils.web_helper import update_user
from .models import Customer, SaleRecord, Business


@receiver(post_save, sender=Customer)
def save_customer(sender, instance, **kwargs):
    update_user(instance=instance)


@receiver(post_save, sender=Business)
def save_business(sender, instance, **kwargs):
    url = f'{settings.RAPID_BASE_URL}survey?business={instance.id}&customer=empty'
    UrlData.objects.generate(url=url).slug


@receiver(pre_save, sender=SaleRecord)
def save_sale(sender, instance: SaleRecord, *args, **kwargs):
    customer: Customer = instance.customer
    if instance.is_verified and customer:
        sale: SaleRecord = SaleRecord.objects.filter(id=instance.id).first()
        if sale is None or sale.is_verified is False:
            if customer.business.loyalty_model == Business.REWARDS_PRICE_TYPE.POINT.value:
                process_point(customer, instance.amount)
            elif customer.business.loyalty_model == Business.REWARDS_PRICE_TYPE.STAMP.value:
                process_stamp(customer)


def process_point(customer: Customer, amount):
    if customer.business.point_amount_value != 0 and amount and amount > 0:
        point_divider = customer.business.point_amount_value
        amount = int(amount)
        points = int(amount / point_divider)
        customer.loyalty_weight = customer.loyalty_weight + points
        customer.save(update_fields=['loyalty_weight'])


def process_stamp(customer: Customer):
    customer.loyalty_weight = customer.loyalty_weight + 1
    customer.save(update_fields=['loyalty_weight'])
