<?php

namespace Shm\ShmChat;

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

class Member
{
    public function __construct(
        public mixed $owner,
        public string $ownerCollection,
        public bool $admin = false,
    ) {
    }

    public static function of(mixed $owner, string $ownerCollection, bool $admin = false): self
    {
        return new self($owner, $ownerCollection, $admin);
    }

    public static function fromAuth(): self
    {
        return new self(Auth::getAuthID(), Auth::getAuthCollection());
    }

    public function admin(bool $admin = true): self
    {
        $this->admin = $admin;

        return $this;
    }

    /**
     * @return array{owner: mixed, ownerCollection: string, isAdmin: bool}
     */
    public function toMemberDocument(): array
    {
        return [
            ShmChannelsField::EL_MEMBERS__OWNER => mDB::id($this->owner),
            ShmChannelsField::EL_MEMBERS__OWNER_COLLECTION => $this->ownerCollection,
            ShmChannelsField::EL_MEMBERS__IS_ADMIN => $this->admin,
        ];
    }

    public function ownerKey(): string
    {
        return (string) $this->owner;
    }

    public function matches(object $member): bool
    {
        return (string) (ShmChannelsField::EL_MEMBERS__OWNER_GET($member, '') ?? '') === $this->ownerKey()
            && (ShmChannelsField::EL_MEMBERS__OWNER_COLLECTION_GET($member) ?? null) === $this->ownerCollection;
    }
}
