<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;
use PDO;
use Throwable;

final class FeatureFlagService
{
    /** @return list<array<string,mixed>> */
    public function all(): array
    {
        try {
            $stmt = Database::connection()->query(
                "SELECT flag_key, label, description, enabled, scope, updated_at
                 FROM axiom_feature_flags
                 ORDER BY label ASC"
            );
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable) {
            return [];
        }
    }

    public function enabled(string $key, bool $default = false): bool
    {
        try {
            $stmt = Database::connection()->prepare('SELECT enabled FROM axiom_feature_flags WHERE flag_key=:flag LIMIT 1');
            $stmt->execute(['flag' => $key]);
            $value = $stmt->fetchColumn();
            return $value === false ? $default : (bool)$value;
        } catch (Throwable) {
            return $default;
        }
    }
}
