from fastapi import APIRouter, Depends, HTTPException, status

from app.api.dependencies.auth import get_access_token
from app.api.dependencies.permissions import require_permission
from app.application.admin.sites import SiteService
from app.schemas.auth import AuthenticatedUser
from app.schemas.admin import SiteListResponse, SiteRead

router = APIRouter()
service = SiteService()


@router.get("", response_model=SiteListResponse)
async def list_sites(
    access_token: str = Depends(get_access_token),
    _: AuthenticatedUser = Depends(require_permission("can_manage_sites")),
) -> SiteListResponse:
    items = await service.list_sites(access_token=access_token)
    return SiteListResponse(items=items)


@router.get("/{site_id}", response_model=SiteRead)
async def get_site(
    site_id: str,
    access_token: str = Depends(get_access_token),
    _: AuthenticatedUser = Depends(require_permission("can_manage_sites")),
) -> SiteRead:
    item = await service.get_site(site_id, access_token=access_token)
    if not item:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Site '{site_id}' not found.",
        )
    return item
