import datetime
import fastapi
import pydantic
import typing

from app.storage.mongo import tasks
from app.utils import time


class RequestBody(pydantic.BaseModel):
    payload: dict
    seconds_to_execute: int
    delay: int|None = None


router = fastapi.APIRouter()


@router.post('/api/v1/put', status_code=fastapi.status.HTTP_202_ACCEPTED)
async def execute(body: RequestBody, queue: typing.Annotated[str, fastapi.Header()]):
    now = time.now()
    await tasks.add_task(
        task=tasks.Task(
            queue=queue, 
            payload=body.payload, 
            put_at=now, 
            available_from=(now + datetime.timedelta(seconds=body.delay)) if body.delay else now,
            seconds_to_execute=body.seconds_to_execute,
        ),
    )
