<?php

namespace Shm\ShmChat\SchemaChat;

use Shm\Collection\Collection;
use Shm\Shm;
use Shm\ShmChat\ShmChat;
use Shm\ShmDB\mDB;
use Shm\ShmTypes\Classes\ShmEventPayload;
use Shm\ShmTypes\StructureType;

class ShmChannelMessages extends Collection
{




    public function schema(): ?StructureType
    {
        $schema = Shm::structure([

            "channel" => ShmChannels::ID(),
            "owner" => Shm::ID(),
            "ownerCollection" => Shm::string(),
            "text" => Shm::string()->title("Текст сообщения"),
            "type" => Shm::enum([
                "regular" => "Обычное",
                "system" => "Системное",
            ])->title("Тип сообщения")->default("regular"),
            "attachments" => Shm::arrayOf(Shm::fileDocument())->title("Вложения"),
            "reply" => ShmChannelMessages::ID(),

            'voice' => Shm::fileAudio(),

            "actions" => Shm::arrayOf(
                Shm::structure([
                    "name" => Shm::string()->title("Имя действия"),
                    "type" => Shm::string()->title("Тип")->default("button"),
                    "value" => Shm::string()->title("Значение"),
                    "text" => Shm::string()->title("Текст кнопки"),
                    "style" => Shm::enum([
                        "default" => "По умолчанию",
                        "primary" => "Основная",
                        "danger" => "Опасная"
                    ])->title("Стиль")->default("default")
                ])
            )->title("Кнопки"),

            "reactions" => Shm::arrayOf(
                Shm::structure([
                    "user" => Shm::ID(),
                    "type" => Shm::enum([
                        "heart" => "Сердце",
                        "like" => "Нравится",
                        "laugh" => "Смех",
                        "wow" => "Удивление",
                        "sad" => "Грусть",
                        "angry" => "Злость",
                        "clap" => "Аплодисменты",
                        "party" => "Праздник",
                        "poop" => "Какахa",
                        "fire" => "Огонь"
                    ]),
                    "created_at" => Shm::timestamp()->title("Когда поставлена")
                ])
            )->title("Реакции"),

            'pinned' => Shm::structure([
                'enabled' => Shm::boolean()->title("Закреплено"),
                'user' => Shm::ID()->title("Кто закрепил"),
                'timestamp' => Shm::unixdatetime()->title("Когда закреплено"),
            ]),


            "payload" =>  Shm::structure([
                '*' => Shm::mixed()
            ]),

            //Просмотрено не отправилем, булевое поле, то что сообщение прочитал кто-то кто не отправитель 
            'viewed' => Shm::bool()->title("Прочитано"),


            'deleted' => Shm::ID()->title("Кто удалил"),


        ]);


        $schema->addEventPostInsert(function (ShmEventPayload $payload) {


            $insertDocumentID  = $payload->postInsertPayload->insertIDs[0] ?? null;

            $message = ShmChannelMessages::structure()->findOne(['_id' => $insertDocumentID]);


            if ($message) {
                ShmChannels::structure()->_updateOne(
                    ['_id' => $message->channel],
                    ['$set' => ['lastMessage' =>  $message->_id]]
                );

                ShmChannels::updateUnreadCounts($message->channel);
            }
        });


        return $schema;
    }




    public static function togglePinnedMessage(string $messageId, string $userId): void
    {
        $messageId = mDB::id($messageId);
        $userId = mDB::id($userId);

        $collection = ShmChannelMessages::structure();

        // Сначала ищем сообщение
        $message = $collection->findOne(['_id' => $messageId], ['projection' => ['pinned' => 1]]);

        $isPinned = $message['pinned']['enabled'] ?? false;

        if ($isPinned) {
            // Снять закрепление
            $collection->updateOne(
                ['_id' => $messageId],
                [
                    '$set' => [
                        'pinned' => null
                    ]
                ]
            );
        } else {
            // Установить новое закрепление
            $collection->updateOne(
                ['_id' => $messageId],
                [
                    '$set' => [
                        'pinned' => [
                            'enabled' => true,
                            'user' => $userId,
                            'timestamp' => time()
                        ]
                    ]
                ]
            );
        }
    }
}
