<?php

namespace App\Infrastructure\Health;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use RuntimeException;

final class InfrastructureChecker
{
    public function assertPostgres(): void
    {
        DB::connection()->getPdo();

        $result = DB::selectOne('select 1 as ok');

        if ((int) ($result->ok ?? 0) !== 1) {
            throw new RuntimeException('PostgreSQL query check failed.');
        }
    }

    public function assertRedis(): void
    {
        $pong = Redis::connection()->ping();

        if ($pong !== true && $pong !== 'PONG' && $pong !== '+PONG') {
            throw new RuntimeException('Redis ping failed.');
        }

        $key = 'infrastructure:health:'.uniqid('', true);

        Cache::store('redis')->put($key, 'ok', 10);

        if (Cache::store('redis')->get($key) !== 'ok') {
            throw new RuntimeException('Redis cache read/write failed.');
        }

        Cache::store('redis')->forget($key);
    }

    public function run(): void
    {
        $this->assertPostgres();
        $this->assertRedis();
    }
}
