# app/modules/cms/routes/api/storefront.py
"""
Storefront Content Pages API (Public)

Public endpoints for retrieving content pages in storefront.
No authentication required.
"""

import logging

from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session

from app.api.deps import require_platform
from app.core.database import get_db
from app.modules.cms.schemas import (
    ContentPageListItem,
    PublicContentPageResponse,
)
from app.modules.cms.services import content_page_service

router = APIRouter()
logger = logging.getLogger(__name__)


# ============================================================================
# PUBLIC ENDPOINTS
# ============================================================================


# public - storefront content pages are publicly accessible
@router.get("/navigation", response_model=list[ContentPageListItem])
def get_navigation_pages(
    request: Request,
    platform=Depends(require_platform),
    db: Session = Depends(get_db),
):
    """
    Get list of content pages for navigation (footer/header).

    Uses store from request.state (set by middleware).
    Returns store overrides + platform defaults.
    """
    store = getattr(request.state, "store", None)
    store_id = store.id if store else None
    platform_id = platform.id

    # Get all published pages for this store
    pages = content_page_service.list_pages_for_store(
        db, platform_id=platform_id, store_id=store_id, include_unpublished=False
    )

    return [
        {
            "slug": page.slug,
            "title": page.title,
            "show_in_footer": page.show_in_footer,
            "show_in_header": page.show_in_header,
            "display_order": page.display_order,
        }
        for page in pages
    ]


@router.get("/{slug}", response_model=PublicContentPageResponse)
def get_content_page(
    slug: str,
    request: Request,
    platform=Depends(require_platform),
    db: Session = Depends(get_db),
):
    """
    Get a specific content page by slug.

    Uses store from request.state (set by middleware).
    Returns store override if exists, otherwise platform default.
    """
    store = getattr(request.state, "store", None)
    store_id = store.id if store else None
    platform_id = platform.id

    page = content_page_service.get_page_for_store_or_raise(
        db,
        platform_id=platform_id,
        slug=slug,
        store_id=store_id,
        include_unpublished=False,  # Only show published pages
    )

    return {
        "slug": page.slug,
        "title": page.title,
        "content": page.content,
        "content_format": page.content_format,
        "meta_description": page.meta_description,
        "meta_keywords": page.meta_keywords,
        "published_at": page.published_at.isoformat() if page.published_at else None,
    }
