<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Repository\Database;

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

final class DatabaseAdminRepository implements AdminRepositoryInterface
{
    public function __construct(
        private readonly PDO $pdo,
    ) {
    }

    public function findByTelegramId(int $telegramId): ?Admin
    {
        $stmt = $this->pdo->prepare('SELECT * FROM admins WHERE telegram_id = :telegram_id');
        $stmt->execute(['telegram_id' => $telegramId]);
        $row = $stmt->fetch();

        if ($row === false) {
            return null;
        }

        return new Admin(
            (int) $row['id'],
            (int) $row['telegram_id'],
            (bool) $row['is_owner']
        );
    }

    /**
     * @return Admin[]
     */
    public function getAll(): array
    {
        $stmt = $this->pdo->query('SELECT * FROM admins');
        $rows = $stmt->fetchAll();

        $admins = [];
        foreach ($rows as $row) {
            $admins[] = new Admin(
                (int) $row['id'],
                (int) $row['telegram_id'],
                (bool) $row['is_owner']
            );
        }

        return $admins;
    }

    public function save(Admin $admin): void
    {
        $id = $admin->getId();
        
        if ($id === 0) {
            // Insert
            $stmt = $this->pdo->prepare(
                'INSERT INTO admins (telegram_id, is_owner) VALUES (:telegram_id, :is_owner)'
            );
            $stmt->execute([
                'telegram_id' => $admin->getTelegramId(),
                'is_owner' => $admin->isOwner() ? 1 : 0,
            ]);
        } else {
            // Update (only is_owner can change)
            $stmt = $this->pdo->prepare(
                'UPDATE admins SET is_owner = :is_owner WHERE id = :id'
            );
            $stmt->execute([
                'id' => $id,
                'is_owner' => $admin->isOwner() ? 1 : 0,
            ]);
        }
    }

    public function delete(int $telegramId): void
    {
        $stmt = $this->pdo->prepare('DELETE FROM admins WHERE telegram_id = :telegram_id');
        $stmt->execute(['telegram_id' => $telegramId]);
    }
}

