<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Services\UpdateValidationEngineService;
use Throwable;

final class UpdateValidationEngineController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.view');

        $runId = max(0, (int) ($_GET['run_id'] ?? 0));

        $this->view('platform/update_validation_center', [
            'pageTitle' => 'Enterprise Validation Center',
            'validationData' => (new UpdateValidationEngineService())->dashboard($runId),
        ]);
    }

    public function simulate(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.simulate');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);

        try {
            $packageId = (int) ($_POST['package_id'] ?? 0);

            $result = (new UpdateValidationEngineService())->simulate(
                $packageId,
                (int) (Auth::user()['id'] ?? 0) ?: null
            );

            $_SESSION[$result['ok'] ? 'success' : 'error'] =
                $result['ok']
                    ? 'Simulation réussie : aucune écriture effectuée.'
                    : 'Simulation bloquée : consultez le rapport.';
        } catch (Throwable $error) {
            $_SESSION['error'] =
                'Simulation impossible : ' . $error->getMessage();
        }

        $this->redirect('/administration/plateforme/validation');
    }

    public function liveStart(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.simulate');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);

        try {
            $result = (new \App\Services\Pipeline\LivePipelineMonitorService())->start(
                (int) ($_POST['package_id'] ?? 0),
                (int) (Auth::user()['id'] ?? 0) ?: null
            );
            $this->json($result);
        } catch (Throwable $error) {
            $this->json(['ok' => false, 'error' => $error->getMessage()], 422);
        }
    }

    public function liveAdvance(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.simulate');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);

        try {
            $result = (new \App\Services\Pipeline\LivePipelineMonitorService())->advance(
                (int) ($_POST['run_id'] ?? 0),
                (int) (Auth::user()['id'] ?? 0) ?: null
            );
            $this->json($result);
        } catch (Throwable $error) {
            $this->json(['ok' => false, 'error' => $error->getMessage()], 422);
        }
    }

    public function liveStatus(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.view');

        try {
            $result = (new \App\Services\Pipeline\LivePipelineMonitorService())->status(
                (int) ($_GET['run_id'] ?? 0)
            );
            $this->json($result);
        } catch (Throwable $error) {
            $this->json(['ok' => false, 'error' => $error->getMessage()], 404);
        }
    }

    /**
     * @param array<string,mixed> $payload
     */
    private function json(array $payload, int $status = 200): never
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=UTF-8');
        header('Cache-Control: no-store, private');
        echo json_encode(
            $payload,
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        );
        exit;
    }

}
