<?php

namespace Shm\ShmChat\SchemaChat;

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

class ShmChannels extends Collection
{

    private static bool $indexesEnsured = false;

    public static function ensureIndexes(): void
    {
        if (self::$indexesEnsured) {
            return;
        }
        self::$indexesEnsured = true;


        return;

        $collection = self::_collection();

        self::createIndexIfMissing($collection, [
            'members.owner' => 1,
            'members.ownerCollection' => 1,
            'closed' => 1,
            'updated_at' => -1,
        ]);

        self::createIndexIfMissing($collection, [
            'space' => 1,
            'members.owner' => 1,
        ]);

        self::createIndexIfMissing($collection, [
            'joinableMembers.owner' => 1,
            'joinableMembers.ownerCollection' => 1,
        ]);

        self::createIndexIfMissing($collection, [
            'reference.documentId' => 1,
            'reference.documentCollection' => 1,
        ]);
    }

    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([
            "space" => Shm::string(),
            "name" => Shm::string(),
            'lastMessage' => ShmChannelMessages::ID(),
            "payload" =>  Shm::structure([
                "*" => Shm::mixed()
            ]),
            'reference' => Shm::arrayOf(Shm::structure([
                'documentId' => Shm::ID(),
                'documentCollection' => Shm::string(),
            ])),

            'members' => Shm::arrayOf(Shm::structure([
                "owner" => Shm::ID(),
                "ownerCollection" => Shm::string(),
                "isAdmin" => Shm::bool()->default(false),
            ])),
            'joinableMembers' => Shm::arrayOf(Shm::structure([
                "owner" => Shm::ID(),
                "ownerCollection" => Shm::string(),
                "isAdmin" => Shm::bool()->default(false),
            ])),
            'closed' => Shm::boolean()->default(false),

            'unreadCounts' => Shm::structure([
                '*' => Shm::int()
            ]),

            'pinnedMessageId' => ShmChannelMessages::ID(),
        ]);

        return $schema;
    }

    public static function touchLastMessage($channelId, $messageId): void
    {
        ShmChannels::structure()->updateOne(
            ['_id' => mDB::id($channelId)],
            ['$set' => ['lastMessage' => mDB::id($messageId)]]
        );
    }

    public static function setPinnedMessageId($channelId, $messageId = null): void
    {
        ShmChannels::structure()->updateOne(
            ['_id' => mDB::id($channelId)],
            ['$set' => ['pinnedMessageId' => $messageId !== null ? mDB::id($messageId) : null]]
        );
    }

    public static function zeroUnreadCounts($channelId, $memberId): void
    {
        $memberKey = 'unreadCounts.' . (string) $memberId;

        ShmChannels::structure()->updateOne(
            [
                '_id' => mDB::id($channelId),
                $memberKey => ['$gt' => 0],
            ],
            ['$set' => [$memberKey => 0]]
        );
    }

    public static function getTotalUnreadByOwner($ownerId): int
    {
        $ownerId = mDB::id($ownerId);
        $ownerKey = (string) $ownerId;

        $result = ShmChannels::structure()->aggregate([
            [
                '$match' => [
                    'members.owner' => $ownerId,
                    'closed' => ['$ne' => true],
                ],
            ],
            [
                '$addFields' => [
                    'myUnread' => ['$ifNull' => ['$unreadCounts.' . $ownerKey, 0]],
                ],
            ],
            [
                '$group' => [
                    '_id' => null,
                    'total' => ['$sum' => '$myUnread'],
                ],
            ],
        ])->toArray();

        return (int) ($result[0]['total'] ?? 0);
    }

    /**
     * @param mixed $senderOwnerId
     * @param string|null $senderOwnerCollection
     */
    public static function updateUnreadCounts($channelId, $senderOwnerId = null, $senderOwnerCollection = null): void
    {
        $channel = ShmChannels::structure()->findOne(
            ['_id' => mDB::id($channelId)],
            ['projection' => ['members' => 1]]
        );

        if (!$channel) {
            return;
        }

        $inc = [];
        $senderOwnerId = $senderOwnerId !== null ? (string) $senderOwnerId : null;

        foreach ($channel->members ?? [] as $member) {
            $memberId = (string) $member->owner;

            if (
                $senderOwnerId !== null
                && $memberId === $senderOwnerId
                && ($member->ownerCollection ?? null) === $senderOwnerCollection
            ) {
                continue;
            }

            $inc['unreadCounts.' . $memberId] = 1;
        }

        if ($inc === []) {
            return;
        }

        ShmChannels::structure()->updateOne(
            ['_id' => mDB::id($channelId)],
            ['$inc' => $inc]
        );
    }
}
