<?php

namespace Shm\ShmChat;

use Shm\ShmChat\SchemaChat\ShmChannelsField;
use Shm\ShmDB\mDB;

/**
 * Связь канала с документом MongoDB (поле `reference`).
 */
class Link
{
    public function __construct(
        public mixed $documentId,
        public string $documentCollection,
    ) {
    }

    public static function to(mixed $documentId, string $documentCollection): self
    {
        return new self($documentId, $documentCollection);
    }

    /**
     * @return array{documentId: mixed, documentCollection: string}
     */
    public function toDocument(): array
    {
        return [
            ShmChannelsField::EL_REFERENCE__DOCUMENT_ID => mDB::id($this->documentId),
            ShmChannelsField::EL_REFERENCE__DOCUMENT_COLLECTION => $this->documentCollection,
        ];
    }

    public function documentIdKey(): string
    {
        return (string) $this->documentId;
    }

    public function matches(string|object|array $item): bool
    {
        if (is_string($item)) {
            return $item === $this->documentCollection . '_' . $this->documentIdKey();
        }

        $documentId = ShmChannelsField::EL_REFERENCE__DOCUMENT_ID_GET($item);
        $documentCollection = ShmChannelsField::EL_REFERENCE__DOCUMENT_COLLECTION_GET($item);

        if ($documentId !== null && $documentCollection !== null) {
            return (string) $documentId === $this->documentIdKey()
                && $documentCollection === $this->documentCollection;
        }

        return false;
    }
}
