<?php
/*
 * Copyright 2026 Alessandro Chiapparini <sprint_planer_web@chiapparini.org>
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * See the LICENSE file in the project root for the full license text.
 */

declare(strict_types=1);

namespace App\Repositories;

use PDO;

/**
 * Tiny key/value store for app-wide flags.
 *
 * Currently holds:
 *   task_status_enabled  '0' | '1'  — Phase 18 task-cell colour states.
 *
 * Values are stored as TEXT; callers cast as needed. Keep this thin — config
 * with structured shape belongs in dedicated tables.
 */
final class AppSettingsRepository
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function get(string $key, ?string $default = null): ?string
    {
        $stmt = $this->pdo->prepare('SELECT value FROM app_settings WHERE key = ?');
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        if (!is_array($row)) {
            return $default;
        }
        return (string) $row['value'];
    }

    public function getBool(string $key, bool $default = false): bool
    {
        $v = $this->get($key);
        if ($v === null) {
            return $default;
        }
        return $v === '1' || strtolower($v) === 'true';
    }

    public function getInt(string $key, int $default = 0): int
    {
        $v = $this->get($key);
        if ($v === null || !is_numeric($v)) {
            return $default;
        }
        return (int) $v;
    }

    /** Returns ['before' => ?string, 'after' => string]. */
    public function set(string $key, string $value): array
    {
        $before = $this->get($key);

        if ($before === $value) {
            return ['before' => $before, 'after' => $value];
        }

        $stmt = $this->pdo->prepare(
            'INSERT INTO app_settings (key, value, updated_at) VALUES (?, ?, ?)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at'
        );
        $stmt->execute([$key, $value, gmdate('Y-m-d\TH:i:s\Z')]);
        return ['before' => $before, 'after' => $value];
    }
}
