from django.db import models

class DiccionarioTabla(models.Model):
    nombre_sap = models.CharField(max_length=150)  # NOT NULL en MySQL
    nombre = models.CharField(max_length=150)      # NOT NULL en MySQL
    descripcion = models.TextField(blank=True, null=True)  # DEFAULT NULL
    tipo = models.CharField(max_length=50)         # NOT NULL en MySQL
    origen = models.CharField(max_length=100, blank=True, null=True)
    actualizacion = models.CharField(max_length=50, blank=True, null=True)
    area = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return self.nombre

    class Meta:
        db_table = 'diccionario_tablas'


class DiccionarioCampo(models.Model):
    tabla = models.ForeignKey(
        DiccionarioTabla,
        on_delete=models.CASCADE,
        related_name='campos'
    )
    nombre = models.CharField(max_length=150)      # NOT NULL en MySQL
    descripcion = models.TextField(blank=True, null=True)
    tipo_dato = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return f"{self.tabla.nombre}.{self.nombre}"

    class Meta:
        db_table = 'diccionario_campos'


class DiccionarioRelacion(models.Model):
    campo_origen = models.ForeignKey(
        'DiccionarioCampo',
        on_delete=models.CASCADE,
        related_name='relaciones_origen'
    )
    
    # Mantienes el nombre textual de la tabla destino
    tabla_destino = models.CharField(max_length=255)  # nombre de la tabla destino (texto)
    campo_destino = models.CharField(max_length=255, blank=True, null=True)
    descripcion = models.TextField(blank=True, null=True)

    # Nueva FK opcional a DiccionarioTabla
    fk_tabla = models.ForeignKey(
        'DiccionarioTabla',
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        related_name='relaciones_fk'
    )

    def __str__(self):
        destino = (
            f"{self.tabla_destino}.{self.campo_destino}"
            if self.campo_destino else self.tabla_destino
        )
        return f"{self.campo_origen} → {destino}"

    class Meta:
        db_table = 'diccionario_relaciones'
