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

from app.api.deps import require_session
from app.services.tenant_store import SessionIdentity, TimeclockOverviewQuery, get_tenant_store


router = APIRouter()


def _raise_timeclock_error(exc: ValueError) -> None:
    detail = str(exc)
    status_code = status.HTTP_403_FORBIDDEN if "non puo accedere" in detail.lower() else status.HTTP_400_BAD_REQUEST
    raise HTTPException(status_code=status_code, detail=detail) from exc


@router.get("/status")
def get_timeclock_status(session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    try:
        return get_tenant_store().get_timeclock_status(session)
    except ValueError as exc:
        _raise_timeclock_error(exc)


@router.post("/start")
def start_timeclock_shift(session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    try:
        return get_tenant_store().start_timeclock_shift(session)
    except ValueError as exc:
        _raise_timeclock_error(exc)


@router.post("/stop")
def stop_timeclock_shift(session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    try:
        return get_tenant_store().stop_timeclock_shift(session)
    except ValueError as exc:
        _raise_timeclock_error(exc)


@router.get("/overview")
def get_timeclock_overview(
    user_id: str | None = Query(default=None),
    start_date: str | None = Query(default=None),
    end_date: str | None = Query(default=None),
    limit: int = Query(default=200, ge=1, le=1000),
    session: SessionIdentity = Depends(require_session),
) -> dict[str, object]:
    try:
        query = TimeclockOverviewQuery(user_id=user_id, start_date=start_date, end_date=end_date, limit=limit)
        return get_tenant_store().get_timeclock_overview(session, query)
    except ValueError as exc:
        _raise_timeclock_error(exc)
