from fastapi import APIRouter, Depends, status

from app.exceptions import UserDontHavePermissionException, MessageNotFoundException, UsersIdIsTheSameException
from app.users.chat.dao import ChatDAO
from app.users.chat.shemas import SMessage, SLastMessages

from app.users.dao import UserDAO
from app.users.dependencies import get_current_user
from app.users.auth import validate_user_access_to_chat
from app.users.models import Users

router = APIRouter(
    prefix="/chat",
    tags=["Чат"]
)


# Мусор
@router.get("")
async def root(user: Users = Depends(get_current_user)):
    print(user)
    return user.id


@router.post("", status_code=status.HTTP_201_CREATED)
async def add_message_to_chat(
        chat_id: int,
        message: str,
        user: Users = Depends(get_current_user)
):
    send_message_to_chat = await ChatDAO.send_message(
        user_id=user.id,
        chat_id=chat_id,
        message=message,
    )


@router.delete("/delete_message", status_code=status.HTTP_204_NO_CONTENT)
async def delete_message_from_chat(
        message_id: int,
        user: Users = Depends(get_current_user)
):
    get_message_sender = await ChatDAO.get_message_by_id(message_id=message_id)
    if get_message_sender is None:
        raise MessageNotFoundException
    if get_message_sender["user_id"] != user.id:
        get_user_role = await UserDAO.get_user_role(user_id=user.id)
        if not get_user_role == 1:
            raise UserDontHavePermissionException
    deleted_message = await ChatDAO.delete_message(message_id=message_id)
    return deleted_message


#  Не доделан
@router.post("/create_chat", status_code=status.HTTP_201_CREATED)
async def create_chat(
        user_to_exclude: int,
        user: Users = Depends(get_current_user)
):
    if user.id == user_to_exclude:
        raise UsersIdIsTheSameException
    created_chat = await ChatDAO.create(user_id=user_to_exclude)
    return created_chat


@router.get("/get_last_message/{chat_id}", response_model=list[SMessage])
async def get_last_message(chat_id: int, user: Users = Depends(get_current_user)):
    await validate_user_access_to_chat(chat_id=chat_id, user_id=user.id)
    message = await ChatDAO.get_some_messages(chat_id=chat_id, message_number_from=0, messages_to_get=1)
    if message is None:
        raise MessageNotFoundException
    return message


@router.get("/get_some_messages/{chat_id}", response_model=list[SMessage])
async def get_some_messages(
        chat_id: int, last_messages: SLastMessages = Depends(), user: Users = Depends(get_current_user)
):
    await validate_user_access_to_chat(chat_id=chat_id, user_id=user.id)
    messages = await ChatDAO.get_some_messages(
        chat_id=chat_id,
        message_number_from=last_messages.messages_count,
        messages_to_get=last_messages.messages_to_get
    )
    if not messages:
        raise MessageNotFoundException
    return messages
