<?php

namespace Shm\ShmChat;

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 [
            'documentId' => mDB::id($this->documentId),
            'documentCollection' => $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();
        }

        if (is_array($item)) {
            if (isset($item['documentId'], $item['documentCollection'])) {
                return (string) $item['documentId'] === $this->documentIdKey()
                    && ($item['documentCollection'] ?? null) === $this->documentCollection;
            }

            return false;
        }

        if (isset($item->documentId, $item->documentCollection)) {
            return (string) $item->documentId === $this->documentIdKey()
                && ($item->documentCollection ?? null) === $this->documentCollection;
        }

        return false;
    }
}
