from typing import Optional

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.session import get_db
from app.domain.entities.change_password import ChangePasswordEntity
from app.domain.entities.user import UserEntity
from app.infrastructure.dependencies import get_current_user, require_admin
from app.infrastructure.users_service import UsersService

router = APIRouter()


@router.get(
    '/',
    response_model=list[UserEntity],
    summary='Return all users',
    description='Returns a list of all users',
)
async def get_authenticated_user_data(
        db: AsyncSession = Depends(get_db),
        user=Depends(require_admin),
):
    users_service = UsersService(db)
    return await users_service.get_all_users()


@router.get(
    '/my-data/',
    response_model=Optional[UserEntity],
    summary='Returns current authenticated user data',
    description='Returns current authenticated user data',
)
async def get_authenticated_user_data(
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    users_service = UsersService(db)
    return await users_service.get_by_id(user.id)


@router.post(
    '/change-password/',
    response_model=Optional[UserEntity],
    summary='Change password for user',
    description='Changes password for user',
)
async def get_authenticated_user_data(
        data: ChangePasswordEntity,
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    users_service = UsersService(db)
    return await users_service.change_password(data, user.id)


@router.put(
    '/{user_id}/',
    response_model=Optional[UserEntity],
    summary='Change first_name, last_name or patronymic',
    description='Change first_name, last_name or patronymic for user',
)
async def change_user(
        user_id: int,
        data: UserEntity,
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    users_service = UsersService(db)
    return await users_service.update_user(data, user_id, user.id)


@router.post(
    '/{user_id}/set-is-block/',
    response_model=Optional[UserEntity],
    summary='Set is_blocked flag for user',
    description='Set is_blocked flag for user',
)
async def set_is_blocked(
        user_id: int,
        is_blocked: bool,
        db: AsyncSession = Depends(get_db),
        user=Depends(require_admin),
):
    users_service = UsersService(db)
    return await users_service.set_is_blocked(user_id, is_blocked, user.id)
