<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Repository;

use Bot\Domain\Entity\ForcedJoinChannel;
use Bot\Domain\Repository\ForcedJoinChannelRepositoryInterface;

final class InMemoryForcedJoinChannelRepository implements ForcedJoinChannelRepositoryInterface
{
    /**
     * @var array<int, ForcedJoinChannel>
     */
    private array $channels = [];
    private int $nextId = 1;

    /**
     * @return ForcedJoinChannel[]
     */
    public function findAll(): array
    {
        return array_values($this->channels);
    }

    /**
     * @return ForcedJoinChannel[]
     */
    public function findEnabled(): array
    {
        return array_values(array_filter($this->channels, fn(ForcedJoinChannel $c) => $c->isEnabled()));
    }

    public function findByChannelUsername(string $channelUsername): ?ForcedJoinChannel
    {
        foreach ($this->channels as $channel) {
            if ($channel->getChannelUsername() === $channelUsername) {
                return $channel;
            }
        }
        return null;
    }

    public function findById(int $id): ?ForcedJoinChannel
    {
        return $this->channels[$id] ?? null;
    }

    public function save(ForcedJoinChannel $channel): void
    {
        // اگر channel جدید است (id=0)، ID جدید اختصاص می‌دهیم
        if ($channel->getId() === 0) {
            $newChannel = new ForcedJoinChannel(
                $this->nextId++,
                $channel->getChannelUsername(),
                $channel->getChannelType(),
                $channel->isEnabled(),
            );
            $channel = $newChannel;
        }

        $id = $channel->getId();
        $this->channels[$id] = $channel;
    }

    public function delete(int $id): void
    {
        unset($this->channels[$id]);
    }
}

