from core.database.abc.db_model_dao_abc import DbModelDaoABC
from core.logger import DBLogger
from data.schemas.public.user_space import UserSpace

logger = DBLogger(__name__)


class UserSpaceDao(DbModelDaoABC[UserSpace]):
    def __init__(self):
        DbModelDaoABC.__init__(self, __name__, UserSpace, "public.user_spaces")
        self.attribute(UserSpace.name, str)
        self.attribute(UserSpace.owner_id, int)

    async def get_by_name(self, name: str) -> UserSpace:
        result = await self._db.select_map(
            f"SELECT * FROM {self._table_name} WHERE Name = '{name}'"
        )
        return self.to_object(result[0])

    async def get_users(self, user_space_id: int, with_invitations=True) -> list:
        result = await self._db.select_map(
            f"""
            SELECT u.* 
            FROM administration.users u
            JOIN public.user_spaces_users usu ON u.id = usu.userId
            WHERE usu.userSpaceId = {user_space_id}
            AND usu.deleted = FALSE
            {'' if with_invitations else 'AND usu.invitation IS NULL'}
            """
        )

        from data.schemas.administration.user_dao import userDao

        return [userDao.to_object(x) for x in result]

    async def get_assigned_by_user_id(self, user_id: int):
        result = await self._db.select_map(
            f"""
            SELECT DISTINCT us.*
            FROM public.user_spaces us
            LEFT JOIN public.user_spaces_users usu ON us.id = usu.userSpaceId
            WHERE (usu.userId = {user_id} OR us.ownerId = {user_id})
            AND us.deleted = FALSE;
            """
        )

        return [self.to_object(x) for x in result]


userSpaceDao = UserSpaceDao()
