from django.db import transaction
from django.utils import timezone

from shop.models import ProductView


@transaction.atomic
def record_product_view(shopping_account, product):
    now = timezone.now()
    product_view, _ = ProductView.objects.update_or_create(
        productId=product,
        shoppingAccountId=shopping_account,
        defaults={"viewedDate": now, "updatedDate": now},
        create_defaults={
            "viewedDate": now,
            "createdDate": now,
            "updatedDate": now,
        },
    )
    return product_view

