from django.db import models
import uuid


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

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

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

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

    # Количество и цена
    quantity = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    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')

    # Описание (опционально)
    description = models.TextField(blank=True, default='')
    terminus_schema_id = models.CharField(max_length=255, blank=True, default='')
    terminus_document_id = 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.product_name} - {self.quantity} {self.unit} ({self.status})"
