"""Beauty branch APIs — Phase 14.0."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.api.permissions import require_permissions
from app.permissions.definitions import BRANCHES_CREATE, BRANCHES_DELETE, BRANCHES_UPDATE, BRANCHES_VIEW
from app.schemas.foundation import BeautyBranchCreate, BeautyBranchRead, BeautyBranchUpdate
from app.services.foundation import BeautyBranchService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=BeautyBranchRead, status_code=status.HTTP_201_CREATED)
async def create_hub(
    body: BeautyBranchCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(BRANCHES_CREATE)),
):
    return await BeautyBranchService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[BeautyBranchRead])
async def list_branches(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(BRANCHES_VIEW)),
):
    return await BeautyBranchService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{branch_id}", response_model=BeautyBranchRead)
async def get_hub(
    branch_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(BRANCHES_VIEW)),
):
    return await BeautyBranchService(db).get(tenant_id, branch_id)


@router.patch("/{branch_id}", response_model=BeautyBranchRead)
async def update_hub(
    branch_id: UUID,
    body: BeautyBranchUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(BRANCHES_UPDATE)),
):
    return await BeautyBranchService(db).update(tenant_id, branch_id, body, actor=user)


@router.post("/{branch_id}/delete", response_model=BeautyBranchRead)
async def soft_delete_hub(
    branch_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(BRANCHES_DELETE)),
):
    return await BeautyBranchService(db).soft_delete(tenant_id, branch_id, actor=user)
