<?php

declare(strict_types=1);

namespace Bot\Domain\Service;

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

final class ForcedJoinChannelService
{
    public function __construct(
        private readonly ForcedJoinChannelRepositoryInterface $repository,
    ) {
    }

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

    /**
     * @return ForcedJoinChannel[]
     */
    public function getEnabledChannels(): array
    {
        return $this->repository->findEnabled();
    }

    public function findById(int $id): ?ForcedJoinChannel
    {
        return $this->repository->findById($id);
    }

    public function findByChannelUsername(string $channelUsername): ?ForcedJoinChannel
    {
        return $this->repository->findByChannelUsername($channelUsername);
    }

    public function createChannel(
        string $channelUsername,
        string $channelType = 'channel',
        ?string $inviteLink = null,
    ): ForcedJoinChannel {
        // بررسی اینکه آیا کانال از قبل وجود دارد
        $existing = $this->repository->findByChannelUsername($channelUsername);
        if ($existing !== null) {
            throw new \RuntimeException("کانال {$channelUsername} از قبل وجود دارد!");
        }

        $channel = new ForcedJoinChannel(0, $channelUsername, $channelType, true, $inviteLink);
        $this->repository->save($channel);
        
        // دریافت channel با ID جدید از دیتابیس
        $savedChannel = $this->repository->findByChannelUsername($channelUsername);
        if ($savedChannel === null) {
            throw new \RuntimeException("خطا در ذخیره کانال!");
        }
        
        return $savedChannel;
    }

    public function updateChannel(ForcedJoinChannel $channel): void
    {
        $this->repository->save($channel);
    }

    public function deleteChannel(int $id): bool
    {
        $channel = $this->repository->findById($id);
        if ($channel === null) {
            return false;
        }
        $this->repository->delete($id);
        return true;
    }

    public function toggleChannel(int $id, bool $enabled): bool
    {
        $channel = $this->repository->findById($id);
        if ($channel === null) {
            return false;
        }
        $channel->toggle($enabled);
        $this->repository->save($channel);
        return true;
    }
}

