from snek.system.service import BaseService


class NotificationService(BaseService):
    mapper_name = "notification"

    async def create(self, object_uid, object_type, user_uid, message):
        model = await self.new()
        model["object_uid"] = object_uid
        model["object_type"] = object_type
        model["user_uid"] = user_uid
        model["message"] = message
        if await self.save(model):
            return model
        raise Exception(f"Failed to create notification: {model.errors}.")

    async def create_channel_message(self, channel_message_uid):
        channel_message = await self.services.channel_message.get(
            uid=channel_message_uid
        )
        user = await self.services.user.get(uid=channel_message["user_uid"])
        async for channel_member in self.services.channel_member.find(
            channel_uid=channel_message["channel_uid"],
            is_banned=False,
            is_muted=False,
            deleted_at=None,
        ):
            model = await self.new()
            model["object_uid"] = channel_message_uid
            model["object_type"] = "channel_message"
            model["user_uid"] = channel_member["user_uid"]
            model["message"] = (
                f"New message from {user['nick']} in {channel_member['label']}."
            )
            if await self.save(model):
                return model
            raise Exception(f"Failed to create notification: {model.errors}.")
