from django.db import models
import uuid


class Offer(models.Model):
    """Оффер (предложение) от поставщика в каталоге"""
    STATUS_CHOICES = [
        ('draft', 'Черновик'),
        ('active', 'Активно'),
        ('closed', 'Закрыто'),
        ('cancelled', 'Отменено'),
    ]

    uuid = models.CharField(max_length=100, unique=True, default=uuid.uuid4)
    team_uuid = models.CharField(max_length=100)  # Команда поставщика
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, default='')
    status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='active')

    # Локация отгрузки
    location_uuid = models.CharField(max_length=100)
    location_name = models.CharField(max_length=255, blank=True, default='')

    # Срок действия
    valid_until = models.DateField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'offers'
        ordering = ['-created_at']

    def __str__(self):
        return f"Оффер {self.title} ({self.status})"


class OfferLine(models.Model):
    """Позиция оффера — конкретный товар с ценой и количеством"""
    uuid = models.CharField(max_length=100, unique=True, default=uuid.uuid4)
    offer = models.ForeignKey(Offer, on_delete=models.CASCADE, related_name='lines')

    # Товар
    product_uuid = models.CharField(max_length=100)
    product_name = models.CharField(max_length=255, blank=True, default='')
    category_name = models.CharField(max_length=255, blank=True, default='')

    # Количество и цена
    quantity = models.DecimalField(max_digits=10, decimal_places=2)
    unit = models.CharField(max_length=20, default='ton')
    price_per_unit = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    currency = models.CharField(max_length=3, default='USD')

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'offer_lines'
        ordering = ['id']

    def __str__(self):
        return f"{self.product_name} - {self.quantity} {self.unit}"
