<?php

declare(strict_types=1);

namespace Bot\Domain\Service;

use Bot\Domain\Entity\Admin;
use Bot\Domain\Repository\AdminRepositoryInterface;

final class AdminService
{
    public function __construct(
        private readonly AdminRepositoryInterface $admins,
    ) {
    }

    public function getByTelegramId(int $telegramId): ?Admin
    {
        return $this->admins->findByTelegramId($telegramId);
    }

    public function getOrCreateOwner(int $telegramId): Admin
    {
        $existing = $this->admins->findByTelegramId($telegramId);
        if ($existing instanceof Admin) {
            return $existing;
        }

        $admin = new Admin(0, $telegramId, true);
        $this->admins->save($admin);

        return $admin;
    }

    public function addAdmin(int $telegramId): Admin
    {
        $existing = $this->admins->findByTelegramId($telegramId);
        if ($existing instanceof Admin) {
            return $existing;
        }

        $admin = new Admin(0, $telegramId, false);
        $this->admins->save($admin);

        return $admin;
    }

    public function removeAdmin(int $telegramId): bool
    {
        $admin = $this->admins->findByTelegramId($telegramId);
        if ($admin === null) {
            return false;
        }

        // نمی‌توان owner را حذف کرد
        if ($admin->isOwner()) {
            return false;
        }

        $this->admins->delete($telegramId);
        return true;
    }

    /**
     * @return Admin[]
     */
    public function getAll(): array
    {
        return $this->admins->getAll();
    }
}



