# app/modules/loyalty/models/transaction_category.py
"""
Store-scoped transaction categories.

Merchants configure 4-10 categories per store (e.g., Men, Women,
Accessories, Kids) that sellers select when entering transactions.
"""

from sqlalchemy import (
    Boolean,
    Column,
    ForeignKey,
    Index,
    Integer,
    String,
    UniqueConstraint,
)
from sqlalchemy.dialects.sqlite import JSON
from sqlalchemy.orm import relationship

from app.core.database import Base
from models.database.base import TimestampMixin


class StoreTransactionCategory(Base, TimestampMixin):
    """Product category for loyalty transactions."""

    __tablename__ = "store_transaction_categories"

    id = Column(Integer, primary_key=True, index=True)
    store_id = Column(Integer, ForeignKey("stores.id"), nullable=False)
    name = Column(String(100), nullable=False)
    name_translations = Column(
        JSON,
        nullable=True,
        comment='Language-keyed name dict, e.g. {"en": "Men", "fr": "Hommes"}',
    )
    display_order = Column(Integer, nullable=False, default=0)
    is_active = Column(Boolean, nullable=False, default=True)

    # Relationships
    store = relationship("Store")

    __table_args__ = (
        UniqueConstraint("store_id", "name", name="uq_store_category_name"),
        Index("idx_store_category_store", "store_id", "is_active"),
    )

    def __repr__(self):
        return f"<StoreTransactionCategory(id={self.id}, store={self.store_id}, name='{self.name}')>"

    def get_translated_name(self, lang: str) -> str:
        """Get name in the given language, falling back to self.name."""
        if self.name_translations and isinstance(self.name_translations, dict):
            return self.name_translations.get(lang) or self.name
        return self.name
