from django.db import models
from product_directory.models import Product

class Warehouse(models.Model):
    name = models.CharField(max_length=255, verbose_name="Название склада")
    location = models.CharField(max_length=255, verbose_name="Расположение склада")
    is_active = models.BooleanField(default=True, verbose_name="Активен")

    class Meta:
        verbose_name = "Склад"
        verbose_name_plural = "Склады"

    def __str__(self):
        return self.name


class StorageLocation(models.Model):
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name="storage_locations", verbose_name="Склад")
    name = models.CharField(max_length=255, verbose_name="Место хранения")
    temperature_control = models.BooleanField(default=False, verbose_name="Требуется контроль температуры")

    class Meta:
        verbose_name = "Место хранения"
        verbose_name_plural = "Места хранения"

    def __str__(self):
        return f"{self.name} ({self.warehouse.name})"

class Stock(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Товар")
    quantity = models.PositiveIntegerField(default=0, verbose_name="Количество")
    location = models.CharField(max_length=255, verbose_name="Место хранения")

    def __str__(self):
        return f"{self.product.name} - {self.quantity} шт."

class StockOperation(models.Model):
    OPERATION_TYPE_CHOICES = [
        ('Incoming', 'Приход'),
        ('Outgoing', 'Расход'),
        ('Transfer', 'Перемещение'),
        ('WriteOff', 'Списание'),
    ]

    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        verbose_name="Товар",
        related_name="warehouse_stock_operations"
    )
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, verbose_name="Склад")
    storage_location = models.ForeignKey(StorageLocation, on_delete=models.CASCADE, verbose_name="Место хранения")
    operation_type = models.CharField(max_length=50, choices=OPERATION_TYPE_CHOICES, verbose_name="Тип операции")
    quantity = models.PositiveIntegerField(verbose_name="Количество")
    operation_date = models.DateTimeField(auto_now_add=True, verbose_name="Дата операции")
    expiration_date = models.DateField(blank=True, null=True, verbose_name="Срок годности")
    reason = models.TextField(blank=True, null=True, verbose_name="Причина (для списания)")

    class Meta:
        verbose_name = "Операция с товаром"
        verbose_name_plural = "Операции с товарами"

    def __str__(self):
        return f"{self.operation_type} - {self.product.name} ({self.warehouse.name})"
