from beanie import PydanticObjectId
from fastapi import HTTPException, Depends

from ..core.routes import get_crud_router
from ..user.manager import get_current_user

from .models import ContractDraft, ContractDraftStatus
from .schemas import ContractDraftCreate, ContractDraftRead, ContractDraftUpdate

draft_router = get_crud_router(ContractDraft, ContractDraftCreate, ContractDraftRead, ContractDraftUpdate)

del(draft_router.routes[0])
del(draft_router.routes[2])


@draft_router.post("/", response_description="Contract Draft added to the database")
async def create(item: ContractDraftCreate, user=Depends(get_current_user)) -> dict:
    await item.validate_foreign_key()
    o = await ContractDraft(**item.dict()).create()
    await o.check_is_ready()

    return {"message": "Contract Draft added successfully", "id": o.id}


@draft_router.put("/{id}", response_description="Contract Draft record updated")
async def update(id: PydanticObjectId, req: ContractDraftUpdate, user=Depends(get_current_user)) -> ContractDraftRead:
    req = {k: v for k, v in req.dict().items() if v is not None}
    update_query = {"$set": {
        field: value for field, value in req.items()
    }}

    item = await ContractDraft.get(id)
    if not item:
        raise HTTPException(
            status_code=404,
            detail="Contract Draft record not found!"
        )
    if item.status == ContractDraftStatus.published:
        raise HTTPException(
            status_code=400,
            detail="Contract Draft has already been published"
        )

    await item.update(update_query)
    await item.check_is_ready()

    return ContractDraftRead(**item.dict())
