from fastapi import APIRouter, Body, HTTPException

from src.api.dependacies.db_dep import sessionDep
from src.api.dependacies.task_dep import FilterDep
from src.api.dependacies.user_dep import (
    ActiveUser,
    AdminUser,
)
from src.core.settings import settings
from src.schemas.users import UserUpdate
from src.services.users import UserService

router = APIRouter(prefix=settings.api.v1.users, tags=["Users"])


@router.get("/")
async def get_all_users(session: sessionDep, _: AdminUser):
    users = await UserService(session).get_all_users()
    return users


@router.get("/{id}")
async def get_user_by_id(session: sessionDep, id: int, _: AdminUser):
    user = await UserService(session).get_user_by_filter_or_raise(id=id)
    return user


@router.get("/{id}/tasks")
async def get_user_tasks(
    session: sessionDep, id: int, user: ActiveUser, filters: FilterDep
):
    if user.id != id and user.is_superuser is False:
        raise HTTPException(status_code=403, detail="Forbidden")
    tasks = await UserService(session).get_user_with_tasks(id, **filters.model_dump())
    return tasks.tasks


@router.patch("/{id}")
async def patch_user(
    session: sessionDep,
    id: int,
    user: ActiveUser,
    user_update: UserUpdate = Body(),
):
    if user.id != id and user.is_superuser is False:
        raise HTTPException(status_code=403, detail="Forbidden")
    updated_user = await UserService(session).update_user(
        id=id, update_data=user_update
    )
    return updated_user


@router.delete("/{id}")
async def delete_user(session: sessionDep, id: int, user: AdminUser):
    await UserService(session).delete_user(id)
    return {"message": "User deleted successfully"}
