"""Locker APIs — Phase 9.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.core.security import get_current_user
from app.schemas.foundation import (
    LockerCreate,
    LockerRead,
    LockerUpdate,
    LockerAssignRequest,
)
from app.services.foundation import LockerService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=LockerRead, status_code=status.HTTP_201_CREATED)
async def create_item(
    body: LockerCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[LockerRead])
async def list_items(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).list(tenant_id, offset=pagination.offset, limit=pagination.page_size)


@router.get("/{locker_id}", response_model=LockerRead)
async def get_item(
    locker_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).get(tenant_id, locker_id)


@router.patch("/{locker_id}", response_model=LockerRead)
async def update_item(
    locker_id: UUID,
    body: LockerUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).update(tenant_id, locker_id, body, actor=user)


@router.post("/{locker_id}/delete", response_model=LockerRead)
async def soft_delete_item(
    locker_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).soft_delete(tenant_id, locker_id, actor=user)


@router.post("/{locker_id}/assign", response_model=LockerRead)
async def assign_locker(
    locker_id: UUID,
    body: LockerAssignRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).assign(tenant_id, locker_id, body, actor=user)


@router.post("/{locker_id}/release", response_model=LockerRead)
async def release_locker(
    locker_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LockerService(db).release(tenant_id, locker_id, actor=user)
