from typing import Annotated

from fastapi import APIRouter, Body, Depends, HTTPException

from src.api.dependacies.db_dep import sessionDep
from src.api.dependacies.user_dep import ActiveUser
from src.schemas.tasks import TaskADDRequest, TaskPATCHRequest
from src.services.tasks import TaskService

router = APIRouter(prefix="/tasks", tags=["Tasks"])


@router.get("/{id}")
async def get_task_id(session: sessionDep, id: int, user: ActiveUser):
    task = await TaskService(session).get_task(id)
    if task.user_id != user.id and user.is_superuser is False:
        raise HTTPException(status_code=403, detail="Forbidden")
    return task


@router.post("/")
async def post_task(
    task_data: Annotated[TaskADDRequest, Depends()],
    session: sessionDep,
    user: ActiveUser,
):
    result = await TaskService(session).create_task(
        user_id=user.id, task_data=task_data
    )
    return result


@router.patch("/{id}")
async def patch_task(
    session: sessionDep,
    id: int,
    user: ActiveUser,
    task_data: TaskPATCHRequest = Body(),
):
    if user.is_superuser is False:
        task = await TaskService(session).get_task(id)
        if task.user_id != user.id:
            raise HTTPException(status_code=403, detail="Forbidden")
    updated_task = await TaskService(session).update_task(id, task_data)
    return updated_task


@router.delete("/{id}")
async def delete_task(
    session: sessionDep,
    id: int,
    user: ActiveUser,
):
    if user.is_superuser is False:
        task = await TaskService(session).get_task(id)
        if task.user_id != user.id:
            raise HTTPException(status_code=403, detail="Forbidden")
    await TaskService(session).delete_task(id)
    return {"message": "Task deleted successfully"}
