from __future__ import annotations

from datetime import datetime, timezone
from typing import Optional, List

from sqlalchemy import (
    Integer, String, Text, DateTime, ForeignKey, Index, func, text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from shared.db.base import Base


def utcnow() -> datetime:
    return datetime.now(timezone.utc)


class MarketPlace(Base):
    __tablename__ = "market_places"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    container_type: Mapped[str] = mapped_column(
        String(32), nullable=False, server_default=text("'page'"),
    )
    container_id: Mapped[int] = mapped_column(Integer, nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    slug: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False, server_default=func.now(),
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False, server_default=func.now(),
    )
    deleted_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True,
    )

    nav_tops: Mapped[List["NavTop"]] = relationship(
        "NavTop", back_populates="market",
    )

    __table_args__ = (
        Index("ix_market_places_container", "container_type", "container_id"),
        Index(
            "ux_market_places_slug_active",
            func.lower(slug),
            unique=True,
            postgresql_where=text("deleted_at IS NULL"),
        ),
    )
