# app/modules/cms/models/content_page.py
"""
Content Page Model

Manages static content pages (About, FAQ, Contact, Shipping, Returns, etc.)
with a three-tier hierarchy:

1. Platform Marketing Pages (is_platform_page=True, vendor_id=NULL)
   - Homepage, pricing, platform about, contact
   - Describes the platform/business offering itself

2. Vendor Default Pages (is_platform_page=False, vendor_id=NULL)
   - Generic storefront pages that all vendors inherit
   - About Us, Shipping Policy, Return Policy, etc.

3. Vendor Override/Custom Pages (is_platform_page=False, vendor_id=set)
   - Vendor-specific customizations
   - Either overrides a default or is a completely custom page

Features:
- Multi-platform support (each platform has its own pages)
- Three-tier content resolution
- Rich text content (HTML/Markdown)
- SEO metadata
- Published/Draft status
- Navigation placement (header, footer, legal)
"""

from datetime import UTC, datetime

from sqlalchemy import (
    JSON,
    Boolean,
    Column,
    DateTime,
    ForeignKey,
    Index,
    Integer,
    String,
    Text,
    UniqueConstraint,
)
from sqlalchemy.orm import relationship

from app.core.database import Base


class ContentPage(Base):
    """
    Content pages with three-tier hierarchy.

    Page Types:
    1. Platform Marketing Page: platform_id=X, vendor_id=NULL, is_platform_page=True
       - Platform's own pages (homepage, pricing, about)
    2. Vendor Default Page: platform_id=X, vendor_id=NULL, is_platform_page=False
       - Fallback pages for vendors who haven't customized
    3. Vendor Override/Custom: platform_id=X, vendor_id=Y, is_platform_page=False
       - Vendor-specific content

    Resolution Logic:
    1. Check for vendor override (platform_id + vendor_id + slug)
    2. Fall back to vendor default (platform_id + vendor_id=NULL + is_platform_page=False)
    3. If neither exists, return 404
    """

    __tablename__ = "content_pages"

    id = Column(Integer, primary_key=True, index=True)

    # Platform association (REQUIRED - determines which platform this page belongs to)
    platform_id = Column(
        Integer,
        ForeignKey("platforms.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
        comment="Platform this page belongs to",
    )

    # Vendor association (NULL = platform page or vendor default)
    vendor_id = Column(
        Integer,
        ForeignKey("vendors.id", ondelete="CASCADE"),
        nullable=True,
        index=True,
        comment="Vendor this page belongs to (NULL for platform/default pages)",
    )

    # Distinguish platform marketing pages from vendor defaults
    is_platform_page = Column(
        Boolean,
        default=False,
        nullable=False,
        comment="True = platform marketing page (homepage, pricing); False = vendor default or override",
    )

    # Page identification
    slug = Column(
        String(100), nullable=False, index=True
    )  # about, faq, contact, shipping, returns, etc.
    title = Column(String(200), nullable=False)

    # Content
    content = Column(Text, nullable=False)  # HTML or Markdown
    content_format = Column(String(20), default="html")  # html, markdown

    # Template selection (for landing pages)
    # Options: 'default', 'minimal', 'modern', 'full'
    # Only used for landing pages (slug='landing' or 'home')
    template = Column(String(50), default="default", nullable=False)

    # Homepage sections (structured JSON for section-based editing)
    # Only used for homepage (slug='home'). Contains hero, features, pricing, cta sections
    # with multi-language support via TranslatableText pattern
    sections = Column(
        JSON,
        nullable=True,
        default=None,
        comment="Structured homepage sections (hero, features, pricing, cta) with i18n",
    )

    # SEO
    meta_description = Column(String(300), nullable=True)
    meta_keywords = Column(String(300), nullable=True)

    # Publishing
    is_published = Column(Boolean, default=False, nullable=False)
    published_at = Column(DateTime(timezone=True), nullable=True)

    # Ordering (for menus, footers)
    display_order = Column(Integer, default=0, nullable=False)
    show_in_footer = Column(Boolean, default=True, nullable=False)
    show_in_header = Column(Boolean, default=False, nullable=False)
    show_in_legal = Column(Boolean, default=False, nullable=False)  # Bottom bar with copyright

    # Timestamps
    created_at = Column(
        DateTime(timezone=True),
        default=lambda: datetime.now(UTC),
        nullable=False,
    )
    updated_at = Column(
        DateTime(timezone=True),
        default=lambda: datetime.now(UTC),
        onupdate=lambda: datetime.now(UTC),
        nullable=False,
    )

    # Author tracking (admin or vendor user who created/updated)
    created_by = Column(
        Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
    )
    updated_by = Column(
        Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
    )

    # Relationships
    platform = relationship("Platform", back_populates="content_pages")
    vendor = relationship("Vendor", back_populates="content_pages")
    creator = relationship("User", foreign_keys=[created_by])
    updater = relationship("User", foreign_keys=[updated_by])

    # Constraints
    __table_args__ = (
        # Unique combination: platform + vendor + slug
        # Platform pages: platform_id + vendor_id=NULL + is_platform_page=True
        # Vendor defaults: platform_id + vendor_id=NULL + is_platform_page=False
        # Vendor overrides: platform_id + vendor_id + slug
        UniqueConstraint("platform_id", "vendor_id", "slug", name="uq_platform_vendor_slug"),
        # Indexes for performance
        Index("idx_platform_vendor_published", "platform_id", "vendor_id", "is_published"),
        Index("idx_platform_slug_published", "platform_id", "slug", "is_published"),
        Index("idx_platform_page_type", "platform_id", "is_platform_page"),
    )

    def __repr__(self):
        vendor_name = self.vendor.name if self.vendor else "PLATFORM"
        return f"<ContentPage(id={self.id}, vendor={vendor_name}, slug={self.slug}, title={self.title})>"

    @property
    def is_vendor_default(self):
        """Check if this is a vendor default page (fallback for all vendors)."""
        return self.vendor_id is None and not self.is_platform_page

    @property
    def is_vendor_override(self):
        """Check if this is a vendor-specific override or custom page."""
        return self.vendor_id is not None

    @property
    def page_tier(self) -> str:
        """Get the tier level of this page for display purposes."""
        if self.is_platform_page:
            return "platform"
        elif self.vendor_id is None:
            return "vendor_default"
        else:
            return "vendor_override"

    def to_dict(self):
        """Convert to dictionary for API responses."""
        return {
            "id": self.id,
            "platform_id": self.platform_id,
            "platform_code": self.platform.code if self.platform else None,
            "platform_name": self.platform.name if self.platform else None,
            "vendor_id": self.vendor_id,
            "vendor_name": self.vendor.name if self.vendor else None,
            "slug": self.slug,
            "title": self.title,
            "content": self.content,
            "content_format": self.content_format,
            "template": self.template,
            "sections": self.sections,
            "meta_description": self.meta_description,
            "meta_keywords": self.meta_keywords,
            "is_published": self.is_published,
            "published_at": (
                self.published_at.isoformat() if self.published_at else None
            ),
            "display_order": self.display_order,
            "show_in_footer": self.show_in_footer or False,
            "show_in_header": self.show_in_header or False,
            "show_in_legal": self.show_in_legal or False,
            "is_platform_page": self.is_platform_page,
            "is_vendor_default": self.is_vendor_default,
            "is_vendor_override": self.is_vendor_override,
            "page_tier": self.page_tier,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "created_by": self.created_by,
            "updated_by": self.updated_by,
        }
