from __future__ import annotations

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

from ...db import get_session
from ...auth_security import require_account, require_user
from .l2a import make_role_dependency
from ...services.approvals_service import ApprovalsService


router = APIRouter(prefix="/api/v2/approvals", tags=["Approvals"])
require_admin_or_manager = make_role_dependency("admin", "manager")


@router.get("/pending", dependencies=[Depends(require_admin_or_manager)])
async def list_pending(
    limit: int = 50,
    offset: int = 0,
    account_id: str = Depends(require_account),
    db: AsyncSession = Depends(get_session),
):
    svc = ApprovalsService(db)
    return await svc.fetch_pending(account_id, limit, offset)


@router.post(
    "/{suggestion_id}/approve", dependencies=[Depends(require_admin_or_manager)]
)
async def approve(
    suggestion_id: str,
    account_id: str = Depends(require_account),
    user_id: str = Depends(require_user),
    db: AsyncSession = Depends(get_session),
):
    svc = ApprovalsService(db)
    try:
        return await svc.approve(account_id, suggestion_id, user_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Not found")


@router.post(
    "/{suggestion_id}/reject", dependencies=[Depends(require_admin_or_manager)]
)
async def reject(
    suggestion_id: str,
    account_id: str = Depends(require_account),
    user_id: str = Depends(require_user),
    db: AsyncSession = Depends(get_session),
):
    svc = ApprovalsService(db)
    try:
        return await svc.reject(account_id, suggestion_id, user_id)
    except ValueError:
        raise HTTPException(status_code=404, detail="Not found")
