import datetime

from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship

from backend.database import Base


class NewsItem(Base):
    __tablename__ = "news_items"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    headline: Mapped[str] = mapped_column(String(500), nullable=False, index=True)
    summary: Mapped[str] = mapped_column(Text, nullable=False)
    tldr_points: Mapped[str | None] = mapped_column(Text, nullable=True)
    summary_body: Mapped[str | None] = mapped_column(Text, nullable=True)
    source_citation: Mapped[str | None] = mapped_column(Text, nullable=True)
    summary_image_url: Mapped[str | None] = mapped_column(String(2000), nullable=True)
    summary_image_credit: Mapped[str | None] = mapped_column(String(500), nullable=True)
    source_url: Mapped[str | None] = mapped_column(String(2000), nullable=True)
    image_url: Mapped[str | None] = mapped_column(String(2000), nullable=True)
    image_credit: Mapped[str | None] = mapped_column(String(500), nullable=True)
    published_at: Mapped[datetime.datetime] = mapped_column(
        DateTime, nullable=False, default=datetime.datetime.utcnow
    )
    created_at: Mapped[datetime.datetime] = mapped_column(
        DateTime, nullable=False, default=datetime.datetime.utcnow
    )
    archived: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    translations: Mapped[list["NewsTranslation"]] = relationship(
        back_populates="news_item", cascade="all, delete-orphan"
    )


class NewsTranslation(Base):
    __tablename__ = "news_translations"
    __table_args__ = (UniqueConstraint("news_item_id", "language", name="uq_news_item_language"),)

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    news_item_id: Mapped[int] = mapped_column(
        ForeignKey("news_items.id"), nullable=False, index=True
    )
    language: Mapped[str] = mapped_column(String(5), nullable=False, index=True)
    headline: Mapped[str] = mapped_column(String(500), nullable=False)
    summary: Mapped[str] = mapped_column(Text, nullable=False)
    tldr_points: Mapped[str | None] = mapped_column(Text, nullable=True)
    summary_body: Mapped[str | None] = mapped_column(Text, nullable=True)
    source_citation: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_at: Mapped[datetime.datetime] = mapped_column(
        DateTime, nullable=False, default=datetime.datetime.utcnow
    )

    news_item: Mapped[NewsItem] = relationship(back_populates="translations")
