from fastapi import HTTPException

from src.schemas.tasks import Task, TaskADDRequest, TaskPATCHRequest
from src.services.base import BaseService


class TaskService(BaseService):
    async def create_task(self, user_id: int, task_data: TaskADDRequest) -> Task:
        user = await self.session.user.get_one_or_none(id=user_id)
        if user is None:
            raise HTTPException(status_code=404, detail="User not found.")
        data_to_insert = task_data.model_dump(exclude_none=True)
        data_to_insert["user_id"] = user.id
        created_task_orm = await self.session.task.create_one(data_to_insert)
        await self.session.commit()
        return Task.model_validate(created_task_orm)

    async def get_task(self, task_id: int):
        task = await self.session.task.get_one_or_none(id=task_id)
        if task is None:
            raise HTTPException(status_code=404, detail="Task not found.")
        return Task.model_validate(task)

    async def delete_task(self, task_id: int):
        await self.session.task.delete_one(id=task_id)
        await self.session.commit()

    async def update_task(
        self,
        task_id: int,
        task_data: TaskPATCHRequest,
        exclude_unset: bool = True,
    ):
        task = await self.session.task.update_one(
            data=task_data.model_dump(exclude_unset=exclude_unset), id=task_id
        )
        await self.session.commit()
        return Task.model_validate(task)
