from django.db import models
from typing import NoReturn
import uuid


class ProductStock(models.Model):
    id = models.UUIDField(verbose_name='ID', default=uuid.uuid3, primary_key=True, unique=True, editable=False)
    product = models.ForeignKey(to='products.Product', on_delete=models.DO_NOTHING)
    quantity = models.PositiveIntegerField(verbose_name='Existencias', default=0)
    last_update = models.DateTimeField(verbose_name='Ultima actualizacion', auto_now=True)

    class Meta:
        verbose_name = 'Existencia de productos'
        verbose_name_plural = 'Existencias de productos'
        db_table = 'products_stock'

    def __str__(self) -> str:
        return f'{self.id}'

    def __repr__(self) -> str:
        return f'ProductStock({self.id})'

    @staticmethod
    def update_quantity(product_id: int, operation: str, quantity: int) -> NoReturn:
        try:
            stock = ProductStock.objects.get(product_id=product_id)

            if operation == 'buying':
                stock.quantity += quantity

            else:
                if stock.quantity > 0 and (stock.quantity - quantity >= 0):
                    stock.quantity -= quantity

            stock.save(update_fields=['quantity'])

        except ProductStock.DoesNotExist:
            ProductStock.objects.create(
                product_id=product_id,
                quantity=quantity
            )
