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

from ...db import get_session
from ...auth import get_current_account
from ...services.roles import require_steward
from ...services.rollback_service import RollbackService

router = APIRouter(prefix="/api/v2/rollback", tags=["rollback"])


class RollbackRequest(BaseModel):
    action_batch_id: str
    justification: str


@router.post("")
async def rollback_action_batch(
    body: RollbackRequest,
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
    user=Depends(require_steward),
):
    """Rollback field updates from an action batch"""
    service = RollbackService(db)

    try:
        results = await service.rollback_action_batch(
            body.action_batch_id, user, account_id, body.justification
        )

        return {
            "success": True,
            "rolled_back_count": len(results["rolled_back"]),
            "skipped_count": len(results["skipped"]),
            "error_count": len(results["errors"]),
            "details": results,
        }
    except ValueError as e:
        raise HTTPException(400, str(e))
