<?php

namespace Shm\ShmChat\SchemaChat;

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

class ShmChannelMessages extends Collection
{

    private static bool $indexesEnsured = false;

    public static function ensureIndexes(): void
    {

        //TODO
        return;

        if (self::$indexesEnsured) {
            return;
        }
        self::$indexesEnsured = true;

        $collection = self::_collection();

        self::createIndexIfMissing($collection, [
            'channel' => 1,
            '_id' => -1,
        ]);

        self::createIndexIfMissing($collection, [
            'channel' => 1,
            'owner' => 1,
            'viewed' => 1,
        ]);

        self::createIndexIfMissing($collection, [
            'channel' => 1,
            'clientMessageId' => 1,
        ], [
            'unique' => true,
            'sparse' => true,
        ]);
    }

    public static function findByClientMessageId($channelId, string $clientMessageId): ?object
    {
        return self::structure()->findOne([
            'channel' => mDB::id($channelId),
            'clientMessageId' => $clientMessageId,
        ]) ?: null;
    }

    public static function isDuplicateKeyError(\Throwable $e): bool
    {
        if ((int) $e->getCode() === 11000) {
            return true;
        }

        $message = $e->getMessage();

        return str_contains($message, 'E11000') || str_contains($message, 'duplicate key');
    }

    private static function createIndexIfMissing(\MongoDB\Collection $collection, array $keys, array $options = []): void
    {
        foreach ($collection->listIndexes() as $index) {
            if (($index['key'] ?? []) === $keys) {
                return;
            }
        }

        $collection->createIndex($keys, $options);
    }

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

            "channel" => ShmChannels::ID()->indexed(),
            "clientMessageId" => Shm::string(),
            "owner" => Shm::ID()->indexed(),
            "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::touchLastMessage($message->channel, $message->_id);

                ShmChannels::updateUnreadCounts(
                    $message->channel,
                    $message->owner,
                    $message->ownerCollection ?? null
                );
            }
        });

        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, 'channel' => 1]]
        );

        if (!$message) {
            return;
        }

        $channelId = $message->channel;
        $isPinned = !empty($message->pinned?->enabled);

        if ($isPinned) {
            $collection->updateOne(
                ['_id' => $messageId],
                [
                    '$set' => [
                        'pinned' => null
                    ]
                ]
            );

            ShmChannels::setPinnedMessageId($channelId, null);

            return;
        }

        $collection->updateMany(
            [
                'channel' => mDB::id($channelId),
                '_id' => ['$ne' => $messageId],
                'pinned.enabled' => true,
            ],
            [
                '$set' => [
                    'pinned' => null
                ]
            ]
        );

        $collection->updateOne(
            ['_id' => $messageId],
            [
                '$set' => [
                    'pinned' => [
                        'enabled' => true,
                        'user' => $userId,
                        'timestamp' => time()
                    ]
                ]
            ]
        );

        ShmChannels::setPinnedMessageId($channelId, $messageId);
    }
}
