# app/modules/cms/routes/api/store_content_pages.py
"""
Store Content Pages API

Store Context: Uses token_store_id from JWT token (authenticated store API pattern).
The get_current_store_api dependency guarantees token_store_id is present.

Stores can:
- View their content pages (includes platform defaults)
- Create/edit/delete their own content page overrides
- Preview pages before publishing
"""

import logging

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

from app.api.deps import get_current_store_api, get_db
from app.modules.cms.exceptions import ContentPageNotFoundException
from app.modules.cms.schemas import (
    CMSUsageResponse,
    ContentPageResponse,
    StoreContentPageCreate,
    StoreContentPageUpdate,
)
from app.modules.cms.services import content_page_service
from app.modules.tenancy.models import User  # API-007
from app.modules.tenancy.services.store_service import (
    StoreService,  # MOD-004 - shared platform service
)

store_service = StoreService()

store_content_pages_router = APIRouter(prefix="/content-pages")
logger = logging.getLogger(__name__)


# ============================================================================
# STORE CONTENT PAGES
# ============================================================================


@store_content_pages_router.get("/", response_model=list[ContentPageResponse])
def list_store_pages(
    include_unpublished: bool = Query(False, description="Include draft pages"),
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    List all content pages available for this store.

    Returns store-specific overrides + platform defaults (store overrides take precedence).
    """
    platform_id = current_user.token_platform_id or content_page_service.resolve_platform_id(db, current_user.token_store_id)
    pages = content_page_service.list_pages_for_store(
        db, platform_id=platform_id, store_id=current_user.token_store_id, include_unpublished=include_unpublished
    )

    return [page.to_dict() for page in pages]


@store_content_pages_router.get("/overrides", response_model=list[ContentPageResponse])
def list_store_overrides(
    include_unpublished: bool = Query(False, description="Include draft pages"),
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    List only store-specific content pages (no platform defaults).

    Shows what the store has customized.
    """
    pages = content_page_service.list_all_store_pages(
        db, store_id=current_user.token_store_id, include_unpublished=include_unpublished
    )

    return [page.to_dict() for page in pages]


@store_content_pages_router.get("/usage", response_model=CMSUsageResponse)
def get_cms_usage(
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Get CMS usage statistics for the store.

    Returns page counts and limits based on subscription tier.
    """
    store = store_service.get_store_by_id_optional(db, current_user.token_store_id)
    if not store:
        return CMSUsageResponse(
            total_pages=0,
            custom_pages=0,
            override_pages=0,
            pages_limit=3,
            custom_pages_limit=0,
            can_create_page=False,
            can_create_custom=False,
            usage_percent=0,
            custom_usage_percent=0,
        )

    # Get store's pages
    store_pages = content_page_service.list_all_store_pages(
        db, store_id=current_user.token_store_id, include_unpublished=True
    )

    total_pages = len(store_pages)
    override_pages = sum(1 for p in store_pages if p.is_store_override)
    custom_pages = total_pages - override_pages

    # Get limits from subscription tier
    pages_limit = None
    custom_pages_limit = None
    if store.subscription and store.subscription.tier:
        pages_limit = store.subscription.tier.cms_pages_limit
        custom_pages_limit = store.subscription.tier.cms_custom_pages_limit

    # Calculate can_create flags
    can_create_page = pages_limit is None or total_pages < pages_limit
    can_create_custom = custom_pages_limit is None or custom_pages < custom_pages_limit

    # Calculate usage percentages
    usage_percent = 0 if pages_limit is None else min(100, (total_pages / pages_limit) * 100) if pages_limit > 0 else 100
    custom_usage_percent = 0 if custom_pages_limit is None else min(100, (custom_pages / custom_pages_limit) * 100) if custom_pages_limit > 0 else 100

    return CMSUsageResponse(
        total_pages=total_pages,
        custom_pages=custom_pages,
        override_pages=override_pages,
        pages_limit=pages_limit,
        custom_pages_limit=custom_pages_limit,
        can_create_page=can_create_page,
        can_create_custom=can_create_custom,
        usage_percent=usage_percent,
        custom_usage_percent=custom_usage_percent,
    )


@store_content_pages_router.get("/platform-default/{slug}", response_model=ContentPageResponse)
def get_platform_default(
    slug: str,
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Get the platform default content for a slug.

    Useful for stores to view the original before/after overriding.
    """
    # Get store's platform (raises NoPlatformSubscriptionException if none)
    platform_id = content_page_service.resolve_platform_id_or_raise(db, current_user.token_store_id)

    # Get platform default (store_id=None)
    page = content_page_service.get_store_default_page(
        db, platform_id=platform_id, slug=slug, include_unpublished=True
    )

    if not page:
        raise ContentPageNotFoundException(slug)

    return page.to_dict()


@store_content_pages_router.get("/{slug}", response_model=ContentPageResponse)
def get_page(
    slug: str,
    include_unpublished: bool = Query(False, description="Include draft pages"),
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Get a specific content page by slug.

    Returns store override if exists, otherwise platform default.
    """
    platform_id = current_user.token_platform_id or content_page_service.resolve_platform_id(db, current_user.token_store_id)
    page = content_page_service.get_page_for_store_or_raise(
        db,
        platform_id=platform_id,
        slug=slug,
        store_id=current_user.token_store_id,
        include_unpublished=include_unpublished,
    )

    return page.to_dict()


@store_content_pages_router.post("/", response_model=ContentPageResponse, status_code=201)
def create_store_page(
    page_data: StoreContentPageCreate,
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Create a store-specific content page override.

    This will be shown instead of the platform default for this store.
    """
    page = content_page_service.create_page(
        db,
        slug=page_data.slug,
        title=page_data.title,
        content=page_data.content,
        store_id=current_user.token_store_id,
        content_format=page_data.content_format,
        meta_description=page_data.meta_description,
        meta_description_translations=getattr(page_data, "meta_description_translations", None),
        is_published=page_data.is_published,
        show_in_footer=page_data.show_in_footer,
        show_in_header=page_data.show_in_header,
        show_in_legal=page_data.show_in_legal,
        display_order=page_data.display_order,
        created_by=current_user.id,
    )
    db.commit()

    return page.to_dict()


@store_content_pages_router.put("/{page_id}", response_model=ContentPageResponse)
def update_store_page(
    page_id: int,
    page_data: StoreContentPageUpdate,
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Update a store-specific content page.

    Can only update pages owned by this store.
    """
    # Update with ownership check in service layer
    page = content_page_service.update_store_page(
        db,
        page_id=page_id,
        store_id=current_user.token_store_id,
        title=page_data.title,
        content=page_data.content,
        content_format=page_data.content_format,
        meta_description=page_data.meta_description,
        meta_description_translations=getattr(page_data, "meta_description_translations", None),
        is_published=page_data.is_published,
        show_in_footer=page_data.show_in_footer,
        show_in_header=page_data.show_in_header,
        show_in_legal=page_data.show_in_legal,
        display_order=page_data.display_order,
        updated_by=current_user.id,
    )
    db.commit()

    return page.to_dict()


@store_content_pages_router.delete("/{page_id}", status_code=204)
def delete_store_page(
    page_id: int,
    current_user: User = Depends(get_current_store_api),
    db: Session = Depends(get_db),
):
    """
    Delete a store-specific content page.

    Can only delete pages owned by this store.
    After deletion, platform default will be shown (if exists).
    """
    # Delete with ownership check in service layer
    content_page_service.delete_store_page(db, page_id, current_user.token_store_id)
    db.commit()
