import uuid
from datetime import datetime

from sqlalchemy import String, DateTime, func, JSON
from sqlalchemy import Uuid
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import TypeDecorator

from app.database import Base


class JSONType(TypeDecorator):
    """A JSON type that uses JSONB on PostgreSQL and JSON on other databases."""
    impl = JSON
    cache_ok = True

    def load_dialect_impl(self, dialect):
        if dialect.name == "postgresql":
            return dialect.type_descriptor(JSONB())
        return dialect.type_descriptor(JSON())


class Brand(Base):
    __tablename__ = "brands"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        primary_key=True,
        default=uuid.uuid4,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        nullable=False,
    )
    name: Mapped[str] = mapped_column(String(50), nullable=False)
    aliases: Mapped[list] = mapped_column(JSONType, default=list, nullable=False)
    website: Mapped[str | None] = mapped_column(String(500), nullable=True)
    industry: Mapped[str | None] = mapped_column(String(50), nullable=True)
    platforms: Mapped[list] = mapped_column(JSONType, default=list, nullable=False)
    frequency: Mapped[str] = mapped_column(String(20), default="weekly", nullable=False)
    status: Mapped[str] = mapped_column(String(20), default="active", nullable=False)
    last_queried_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    next_query_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        nullable=False,
    )
    updated_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    # Relationship to Competitor - one brand can have multiple competitors
    competitors: Mapped[list["Competitor"]] = relationship(
        "Competitor", back_populates="brand", cascade="all, delete-orphan"
    )

    # Relationship to Suggestion - one brand can have multiple suggestions
    suggestions: Mapped[list["Suggestion"]] = relationship(
        "Suggestion", back_populates="brand", cascade="all, delete-orphan"
    )


# Import at bottom to avoid circular import
from app.models.competitor import Competitor  # noqa: E402, F401
from app.models.suggestion import Suggestion  # noqa: E402, F401
