# suma_browser/models/ghost_membership_entities.py

from datetime import datetime
from typing import Optional

from sqlalchemy import (
    Integer, String, Text, Boolean, DateTime, ForeignKey, UniqueConstraint
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.ext.associationproxy import association_proxy

from shared.db.base import Base


# -----------------------
# Labels (simple M2M)
# -----------------------

class GhostLabel(Base):
    __tablename__ = "ghost_labels"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    ghost_id: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    slug: Mapped[Optional[str]] = mapped_column(String(255))
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)
    updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)

    # Back-populated by User.labels
    users = relationship("User", secondary="user_labels", back_populates="labels", lazy="selectin")


class UserLabel(Base):
    __tablename__ = "user_labels"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
    label_id: Mapped[int] = mapped_column(ForeignKey("ghost_labels.id", ondelete="CASCADE"), index=True)

    __table_args__ = (
        UniqueConstraint("user_id", "label_id", name="uq_user_label"),
    )


# -----------------------
# Newsletters (association object + proxy)
# -----------------------

class GhostNewsletter(Base):
    __tablename__ = "ghost_newsletters"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    ghost_id: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    slug: Mapped[Optional[str]] = mapped_column(String(255))
    description: Mapped[Optional[str]] = mapped_column(Text)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)
    updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)

    # Association-object side (one-to-many)
    user_newsletters = relationship(
        "UserNewsletter",
        back_populates="newsletter",
        cascade="all, delete-orphan",
        lazy="selectin",
    )

    # Convenience: list-like proxy of Users via association rows (read-only container)
    users = association_proxy("user_newsletters", "user")


class UserNewsletter(Base):
    __tablename__ = "user_newsletters"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
    newsletter_id: Mapped[int] = mapped_column(ForeignKey("ghost_newsletters.id", ondelete="CASCADE"), index=True)
    subscribed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)

    __table_args__ = (
        UniqueConstraint("user_id", "newsletter_id", name="uq_user_newsletter"),
    )

    # Bidirectional links for the association object
    user = relationship("User", back_populates="user_newsletters", lazy="selectin")
    newsletter = relationship("GhostNewsletter", back_populates="user_newsletters", lazy="selectin")


# -----------------------
# Tiers & Subscriptions
# -----------------------

class GhostTier(Base):
    __tablename__ = "ghost_tiers"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    ghost_id: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    slug: Mapped[Optional[str]] = mapped_column(String(255))
    type: Mapped[Optional[str]] = mapped_column(String(50))      # e.g. free, paid
    visibility: Mapped[Optional[str]] = mapped_column(String(50))


class GhostSubscription(Base):
    __tablename__ = "ghost_subscriptions"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    ghost_id: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
    status: Mapped[Optional[str]] = mapped_column(String(50))
    tier_id: Mapped[Optional[int]] = mapped_column(ForeignKey("ghost_tiers.id", ondelete="SET NULL"), index=True)
    cadence: Mapped[Optional[str]] = mapped_column(String(50))   # month, year
    price_amount: Mapped[Optional[int]] = mapped_column(Integer)
    price_currency: Mapped[Optional[str]] = mapped_column(String(10))
    stripe_customer_id: Mapped[Optional[str]] = mapped_column(String(255), index=True)
    stripe_subscription_id: Mapped[Optional[str]] = mapped_column(String(255), index=True)
    raw: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)

    # Relationships
    user = relationship("User", back_populates="subscriptions", lazy="selectin")
    tier = relationship("GhostTier", lazy="selectin")
