<?php

declare(strict_types=1);

namespace App\Controllers;

use Database;
use Response;
use PDO;
use Exception;

/**
 * HealthController
 *
 * Endpoint de vérification de santé de l'API
 * Route publique pour permettre le monitoring automatique
 */
class HealthController
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    /**
     * Vérifie la santé de l'API
     * GET /api/health
     *
     * @return void
     */
    public function check(): void
    {
        $checks = [
            'api' => 'ok',
            'database' => $this->checkDatabase(),
            'directories' => $this->checkDirectories()
        ];

        // Déterminer le statut global
        $status = in_array('error', $checks, true) ? 'error' : 'ok';
        $httpCode = $status === 'ok' ? 200 : 503;

        Response::json([
            'status' => $status,
            'checks' => $checks,
            'timestamp' => date('Y-m-d H:i:s'),
            'environment' => $this->getEnvironment()
        ], $httpCode);
    }

    /**
     * Vérifie la connexion à la base de données
     *
     * @return string 'ok' ou 'error'
     */
    private function checkDatabase(): string
    {
        try {
            $db = Database::getInstance();
            $stmt = $db->query("SELECT 1");
            return $stmt ? 'ok' : 'error';
        } catch (Exception $e) {
            error_log("Health check database error: " . $e->getMessage());
            return 'error';
        }
    }

    /**
     * Vérifie l'accessibilité des dossiers critiques
     *
     * @return string 'ok' ou 'error'
     */
    private function checkDirectories(): string
    {
        $basePath = __DIR__ . '/../../';
        $requiredDirs = ['logs', 'uploads'];

        foreach ($requiredDirs as $dir) {
            $fullPath = $basePath . $dir;

            if (!is_dir($fullPath)) {
                error_log("Health check: Directory not found: $fullPath");
                return 'error';
            }

            if (!is_writable($fullPath)) {
                error_log("Health check: Directory not writable: $fullPath");
                return 'error';
            }
        }

        return 'ok';
    }

    /**
     * Détecte l'environnement actuel
     *
     * @return string 'dev', 'recette' ou 'production'
     */
    private function getEnvironment(): string
    {
        $host = $_SERVER['HTTP_HOST'] ?? 'unknown';

        if (str_contains($host, 'dapp.geosector.fr')) {
            return 'dev';
        } elseif (str_contains($host, 'rapp.geosector.fr')) {
            return 'recette';
        } elseif (str_contains($host, 'app3.geosector.fr') || str_contains($host, 'app.geosector.fr')) {
            return 'production';
        }

        return 'unknown';
    }
}
