from sqlalchemy import BigInteger, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.models.base import Base, TimestampMixin, TenantMixin


class ProductMediaRole(Base, TenantMixin, TimestampMixin):
    __tablename__ = "product_media_roles"
    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uk_product_media_role_code"),
        Index("ix_product_media_role_tenant_active", "tenant_id", "is_active"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    code: Mapped[str] = mapped_column(String(80), nullable=False)
    label: Mapped[str] = mapped_column(String(160), nullable=False)
    description: Mapped[str | None] = mapped_column(String(500), nullable=True)
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    is_active: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=1)

    items = relationship("ProductMediaRoleItem", back_populates="role", lazy="noload")


class ProductMediaRoleItem(Base, TenantMixin, TimestampMixin):
    __tablename__ = "product_media_role_items"
    __table_args__ = (
        Index("ix_product_media_role_item_product", "tenant_id", "product_id", "sort_order"),
        Index("ix_product_media_role_item_role", "tenant_id", "role_id", "is_active"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    product_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("products.id", ondelete="CASCADE"), nullable=False)
    role_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("product_media_roles.id", ondelete="RESTRICT"), nullable=False)
    image_url: Mapped[str] = mapped_column(String(500), nullable=False)
    alt_text: Mapped[str | None] = mapped_column(String(200), nullable=True)
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    is_active: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=1)

    role = relationship("ProductMediaRole", back_populates="items", lazy="joined")
