# app/modules/messaging/routes/pages/store.py
"""
Messaging Store Page Routes (HTML rendering).

Store pages for messaging management:
- Messages list
- Conversation detail
- Email templates
"""

from fastapi import APIRouter, Depends, Path, Request
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session

from app.api.deps import (
    get_current_store_from_cookie_or_header,
    get_db,
    get_resolved_store_code,
)
from app.modules.core.utils.page_context import get_store_context
from app.modules.tenancy.models import User
from app.templates_config import templates

router = APIRouter()


# ============================================================================
# MESSAGING
# ============================================================================


@router.get(
    "/messages", response_class=HTMLResponse, include_in_schema=False
)
async def store_messages_page(
    request: Request,
    store_code: str = Depends(get_resolved_store_code),
    current_user: User = Depends(get_current_store_from_cookie_or_header),
    db: Session = Depends(get_db),
):
    """
    Render messages page.
    JavaScript loads conversations and messages via API.
    """
    return templates.TemplateResponse(
        "messaging/store/messages.html",
        get_store_context(request, db, current_user, store_code),
    )


@router.get(
    "/messages/{conversation_id}",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def store_message_detail_page(
    request: Request,
    store_code: str = Depends(get_resolved_store_code),
    conversation_id: int = Path(..., description="Conversation ID"),
    current_user: User = Depends(get_current_store_from_cookie_or_header),
    db: Session = Depends(get_db),
):
    """
    Render message detail page.
    Shows the full conversation thread.
    """
    return templates.TemplateResponse(
        "messaging/store/messages.html",
        get_store_context(
            request, db, current_user, store_code, conversation_id=conversation_id
        ),
    )


# ============================================================================
# EMAIL TEMPLATES
# ============================================================================


@router.get(
    "/email-templates",
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def store_email_templates_page(
    request: Request,
    store_code: str = Depends(get_resolved_store_code),
    current_user: User = Depends(get_current_store_from_cookie_or_header),
    db: Session = Depends(get_db),
):
    """
    Render store email templates customization page.
    Allows stores to override platform email templates.
    """
    return templates.TemplateResponse(
        "messaging/store/email-templates.html",
        get_store_context(request, db, current_user, store_code),
    )
