# app/modules/catalog/models/product_media.py
"""
Product-Media association model.

Links media files to products with usage type tracking
(main image, gallery, variant images, etc.)

This model lives in the catalog module because:
- It's an association specific to products
- Catalog owns the relationship between its products and media
- CMS provides generic media storage, catalog defines how it uses media
"""

from sqlalchemy import (
    Column,
    ForeignKey,
    Index,
    Integer,
    String,
    UniqueConstraint,
)
from sqlalchemy.orm import relationship

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


class ProductMedia(Base, TimestampMixin):
    """Association between products and media files.

    Tracks which media files are used by which products,
    including the usage type (main image, gallery, variant, etc.)

    This is catalog's association table - CMS doesn't need to know about it.
    """

    __tablename__ = "product_media"

    id = Column(Integer, primary_key=True, index=True)
    product_id = Column(
        Integer,
        ForeignKey("products.id", ondelete="CASCADE"),
        nullable=False,
    )
    media_id = Column(
        Integer,
        ForeignKey("media_files.id", ondelete="CASCADE"),
        nullable=False,
    )

    # Usage type
    usage_type = Column(String(50), nullable=False, default="gallery")
    # Types: main_image, gallery, variant, thumbnail, swatch

    # Display order for galleries
    display_order = Column(Integer, default=0)

    # Variant-specific (if usage_type is variant)
    variant_id = Column(Integer)  # Reference to variant if applicable

    # Relationships
    product = relationship("Product", back_populates="media_associations")
    # MediaFile is generic and doesn't know about ProductMedia
    media = relationship("MediaFile", lazy="joined")

    __table_args__ = (
        UniqueConstraint(
            "product_id", "media_id", "usage_type",
            name="uq_product_media_usage"
        ),
        Index("idx_product_media_product", "product_id"),
        Index("idx_product_media_media", "media_id"),
    )

    def __repr__(self):
        return (
            f"<ProductMedia(product_id={self.product_id}, "
            f"media_id={self.media_id}, usage='{self.usage_type}')>"
        )
