from django.db import models
from shop_management.models.base import DataRoot
from django.conf import settings
import uuid
from django.db import connection
from functools import lru_cache


@lru_cache(maxsize=1)
def shop_id_column_exists():
    try:
        with connection.cursor() as cursor:
            columns = {
                column.name
                for column in connection.introspection.get_table_description(
                    cursor, Shop._meta.db_table
                )
            }
        return "shop_id" in columns
    except Exception:
        return False

class Shop(DataRoot):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='shops')
    assigned_users = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        blank=True,
        related_name="assigned_shops",
        help_text="Users assigned to this shop who can see its data.",
    )
    shop_id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    @property
    def safe_shop_id(self):
        if shop_id_column_exists():
            return self.__dict__.get("shop_id") or getattr(self, "shop_id", None)
        return f"SHOP-{self.pk}"
