from fastapi import APIRouter, Depends, HTTPException, Query, status

from app.api.dependencies.auth import get_access_token
from app.api.dependencies.permissions import require_permission
from app.application.admin.goals import GoalService
from app.schemas.auth import AuthenticatedUser
from app.schemas.admin import GoalListResponse, GoalRead

router = APIRouter()
service = GoalService()


@router.get("", response_model=GoalListResponse)
async def list_goals(
    site_id: str | None = Query(default=None),
    access_token: str = Depends(get_access_token),
    _: AuthenticatedUser = Depends(require_permission("can_manage_goals")),
) -> GoalListResponse:
    items = await service.list_goals(site_id=site_id, access_token=access_token)
    return GoalListResponse(items=items)


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