import uuid
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

# -------------------------------------------------------------
# ABSTRACT MODELS (MOLDES / PEÇAS DE LEGO)
# -------------------------------------------------------------
# Estes modelos NÃO criam tabelas no banco de dados. Eles servem
# APENAS para que os desenvolvedores importem e herdem em seus 
# próprios projetos, garantindo modularidade extrema.
# 
# Exemplo de uso no novo projeto:
# from base.abstract_models import AbstractProductItem
# class MeuProduto(AbstractProductItem):
#     campo_novo = models.CharField(max_length=50)
# -------------------------------------------------------------

# --- PRODUCTS ---

class AbstractProductItem(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=125)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    description = models.CharField(max_length=300, null=True, blank=True)
    image = models.ImageField(upload_to='products/', blank=True, null=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class AbstractInventoryItem(models.Model):

    slug = models.SlugField(unique=True, null=True, blank=True) 
    stock = models.PositiveIntegerField(default=0, null=True, blank=True)

    class Meta:
        abstract = True

    def generate_slug_if_needed(self, base_text_for_slug):
        if not self.slug and base_text_for_slug:
             from django.utils.text import slugify
             base_slug = slugify(base_text_for_slug)
             self.slug = f"{base_slug}-{str(self.id)[:8]}" if hasattr(self, 'id') and self.id else base_slug

class AbstractProductVariation(models.Model):
 
    name = models.CharField(max_length=50) 
    value = models.CharField(max_length=50) 
    price_override = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    stock = models.PositiveIntegerField(default=0)

    class Meta:
        abstract = True

# --- USERS E ENDEREÇO ---

class AbstractAddress(models.Model):
    street = models.CharField(max_length=255)
    number = models.PositiveIntegerField() 
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    zip_code = models.CharField(max_length=20)

    class Meta:
        abstract = True

class AbstractUserSecurityProfile(models.Model):
    is_2fa_enabled = models.BooleanField(default=False)
    otp_code = models.CharField(max_length=6, blank=True, null=True)
    otp_created_at = models.DateTimeField(blank=True, null=True)
    reset_password_token = models.CharField(max_length=100, blank=True, null=True)
    reset_password_expires = models.DateTimeField(blank=True, null=True)

    class Meta:
        abstract = True

# --- ORDERS ---

class AbstractOrder(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    STATUS_CHOICE = [
        ('pending','Pendente'),
        ('preparing','Em preparo'),
        ('ready', 'Pronto'),
        ('delivered', 'Entregue'),
        ('canceled', 'Cancelado'),
    ]
    status = models.CharField(max_length=20, choices=STATUS_CHOICE, default='pending')
    payment_status = models.BooleanField(default=False)

    class Meta:
        abstract = True

class AbstractOrderItem(models.Model):
    quantity = models.PositiveIntegerField(default=1)

    class Meta:
        abstract = True

# --- CART ---

class AbstractCartBase(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

class AbstractCartItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 
    quantity = models.PositiveIntegerField(default=1)

    class Meta:
        abstract = True

# --- CRM ---

class AbstractCRMTag(models.Model):
    name = models.CharField(max_length=50, unique=True)
    color = models.CharField(max_length=7, default="#FFFFFF")

    class Meta:
        abstract = True

class AbstractCRMContact(models.Model):
    internal_notes = models.TextField(blank=True, help_text="Anotações internas sobre o cliente (não visível para ele)")
    lifetime_value = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
    total_orders_count = models.PositiveIntegerField(default=0)
    last_purchase_date = models.DateTimeField(null=True, blank=True)

    class Meta:
        abstract = True

class AbstractCRMInteraction(models.Model):
    INTERACTION_TYPES = [
        ('call', 'Ligação'),
        ('email', 'E-mail'),
        ('whatsapp', 'WhatsApp'),
        ('support', 'Suporte/Ticket'),
        ('meeting', 'Reunião Presencial'),
        ('other', 'Outro'),
    ]
    type = models.CharField(max_length=20, choices=INTERACTION_TYPES)
    subject = models.CharField(max_length=150)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

# --- ERP ---

class AbstractSupplier(models.Model):
    name = models.CharField(max_length=150)
    contact_name = models.CharField(max_length=100, blank=True)
    phone = models.CharField(max_length=20, blank=True, null=True)
    email = models.EmailField(blank=True)
    notes = models.TextField(blank=True)

    class Meta:
        abstract = True

class AbstractInventoryLog(models.Model):
    MOVEMENT_TYPES = [
        ('IN', 'Entrada'),
        ('OUT', 'Saída'),
        ('ADJUST', 'Ajuste de Auditoria'),
    ]
    type = models.CharField(max_length=10, choices=MOVEMENT_TYPES)
    quantity = models.PositiveIntegerField() 
    reason = models.CharField(max_length=200) 
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

class AbstractFinancialTransaction(models.Model):
    TRANSACTION_TYPES = [
        ('INCOME', 'Receita'),
        ('EXPENSE', 'Despesa'),
        ]
    type = models.CharField(max_length=10, choices=TRANSACTION_TYPES)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    description = models.CharField(max_length=200) 
    category = models.CharField(max_length=50, blank=True) 
    date = models.DateField(auto_now_add=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True
