"""Point account APIs — Phase 7.0 shell (no balance mutation)."""
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 (
    LOYALTY_POINT_ACCOUNTS_CREATE,
    LOYALTY_POINT_ACCOUNTS_MANAGE,
    LOYALTY_POINT_ACCOUNTS_UPDATE,
    LOYALTY_POINT_ACCOUNTS_VIEW,
)
from app.schemas.foundation import (
    PointAccountCreate,
    PointAccountRead,
    PointAccountUpdate,
)
from app.services.foundation import PointAccountService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=PointAccountRead, status_code=status.HTTP_201_CREATED)
async def open_point_account(
    body: PointAccountCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_POINT_ACCOUNTS_CREATE)),
):
    return await PointAccountService(db).create(tenant_id, body, actor=user)


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


@router.get("/{account_id}", response_model=PointAccountRead)
async def get_point_account(
    account_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_POINT_ACCOUNTS_VIEW)),
):
    return await PointAccountService(db).get(tenant_id, account_id)


@router.patch("/{account_id}", response_model=PointAccountRead)
async def update_point_account(
    account_id: UUID,
    body: PointAccountUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_POINT_ACCOUNTS_UPDATE)),
):
    return await PointAccountService(db).update(
        tenant_id, account_id, body, actor=user
    )


@router.post("/{account_id}/delete", response_model=PointAccountRead)
async def soft_delete_point_account(
    account_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_POINT_ACCOUNTS_MANAGE)),
):
    return await PointAccountService(db).soft_delete(
        tenant_id, account_id, actor=user
    )
