<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;
use Throwable;

final class DatabaseHealthService
{
    /** @return array<string,mixed> */
    public function report(): array
    {
        try {
            $pdo = Database::connection();
            $version = (string)$pdo->query('SELECT VERSION()')->fetchColumn();
            $database = (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
            $charset = (string)$pdo->query("SELECT @@character_set_database")->fetchColumn();
            $collation = (string)$pdo->query("SELECT @@collation_database")->fetchColumn();
            $tables = (int)$pdo->query(
                "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()"
            )->fetchColumn();
            $integrityTables = ['cda_update_packages', 'cda_backup_jobs', 'axiom_modules', 'axiom_migrations'];
            $missing = [];
            $check = $pdo->prepare(
                'SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:table'
            );
            foreach ($integrityTables as $table) {
                $check->execute(['table' => $table]);
                if ((int)$check->fetchColumn() === 0) {
                    $missing[] = $table;
                }
            }
            return [
                'status' => $missing === [] ? 'ok' : 'warning',
                'database' => $database,
                'server_version' => $version,
                'charset' => $charset,
                'collation' => $collation,
                'tables' => $tables,
                'missing_tables' => $missing,
                'message' => $missing === [] ? 'Structure essentielle disponible.' : 'Tables manquantes : ' . implode(', ', $missing),
            ];
        } catch (Throwable $e) {
            return [
                'status' => 'warning',
                'database' => '',
                'server_version' => '',
                'charset' => '',
                'collation' => '',
                'tables' => 0,
                'missing_tables' => [],
                'message' => $e->getMessage(),
            ];
        }
    }
}
