from fastapi import APIRouter, Depends, HTTPException

from app.core.dependencies import require_admin
from app.modules.content.schemas import ContentPageIn, ContentPagePatchIn
from app.modules.content.service import (
    create_page,
    delete_page,
    get_page_by_slug,
    list_all_pages,
    list_published_pages,
    page_exists,
    page_to_dict,
    update_page,
)

router = APIRouter()


@router.get("/pages")
async def list_pages_route():
    pages = list_published_pages()
    return {"data": [page_to_dict(page) for page in pages]}


@router.get("/pages/manage/all")
async def list_all_pages_route(_admin=Depends(require_admin)):
    pages = list_all_pages()
    return {"data": [page_to_dict(page) for page in pages]}


@router.get("/pages/{slug}")
async def get_page_route(slug: str):
    page = get_page_by_slug(slug)
    if not page:
        raise HTTPException(status_code=404, detail="PAGE_NOT_FOUND")
    return page_to_dict(page)


@router.post("/pages")
async def create_page_route(payload: ContentPageIn, admin=Depends(require_admin)):
    page = create_page(payload.slug, payload.title, payload.body, payload.status, admin.id)
    return page_to_dict(page)


@router.patch("/pages/{page_id}")
async def update_page_route(page_id: str, payload: ContentPagePatchIn, _admin=Depends(require_admin)):
    if not page_exists(page_id):
        raise HTTPException(status_code=404, detail="PAGE_NOT_FOUND")
    page = update_page(page_id, payload.title, payload.body, payload.status)
    return page_to_dict(page)


@router.delete("/pages/{page_id}")
async def delete_page_route(page_id: str, _admin=Depends(require_admin)):
    delete_page(page_id)
    return {"message": "deleted"}
