<?php

namespace Shm\ShmChat;

use Shm\ShmAuth\Auth;
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 [
            'owner' => mDB::id($this->owner),
            'ownerCollection' => $this->ownerCollection,
            'isAdmin' => $this->admin,
        ];
    }

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

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