<?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\Core\TenantContext;
use App\Services\ReleaseAutomationService;
use Throwable;

final class ReleaseAutomationController extends Controller
{
    private function organisationId(): int { return TenantContext::id(); }
    private function actorId(): int { return (int)(Auth::user()['id'] ?? 0); }
    private function requireWriteAccess(): void
    {
        Auth::requireLogin(); Permission::require('updates.install'); Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication(); Csrf::verify($_POST['_csrf'] ?? null);
    }

    public function index(): void
    {
        Auth::requireLogin(); Permission::require('updates.view');
        $service = new ReleaseAutomationService();
        $edit = isset($_GET['edit']) ? $service->find((int)$_GET['edit'], $this->organisationId()) : null;
        $this->view('platform/release_automation', [
            'pageTitle'=>'Automatisation des releases', 'rules'=>$service->listRules($this->organisationId()),
            'logs'=>$service->listLogs($this->organisationId()), 'trains'=>$service->trains($this->organisationId()), 'edit'=>$edit,
        ]);
    }

    public function save(): void
    {
        $this->requireWriteAccess();
        try { (new ReleaseAutomationService())->saveRule($_POST, ((int)($_POST['id']??0))?:null, $this->actorId(), $this->organisationId());
            $_SESSION['success']='Règle d’automatisation enregistrée.'; }
        catch (Throwable $e) { $_SESSION['error']=$e->getMessage(); $_SESSION['automation_old']=$_POST; }
        $this->redirect('/administration/plateforme/release-automation');
    }

    public function status(): void
    {
        $this->requireWriteAccess();
        try { (new ReleaseAutomationService())->setActive(max(1,(int)($_POST['id']??0)), (int)($_POST['active']??0)===1,
                $this->actorId(), $this->organisationId()); $_SESSION['success']='Statut de la règle mis à jour.'; }
        catch (Throwable $e) { $_SESSION['error']=$e->getMessage(); }
        $this->redirect('/administration/plateforme/release-automation');
    }

    public function archive(): void
    {
        $this->requireWriteAccess();
        try { (new ReleaseAutomationService())->archive(max(1,(int)($_POST['id']??0)), $this->actorId(), $this->organisationId());
            $_SESSION['success']='Règle archivée.'; }
        catch (Throwable $e) { $_SESSION['error']=$e->getMessage(); }
        $this->redirect('/administration/plateforme/release-automation');
    }

    public function simulate(): void
    {
        $this->requireWriteAccess();
        try { $result=(new ReleaseAutomationService())->simulate(max(1,(int)($_POST['id']??0)), $this->actorId(), $this->organisationId());
            $_SESSION['success']='Simulation réussie : '.$result['message']; }
        catch (Throwable $e) { $_SESSION['error']='Simulation refusée : '.$e->getMessage(); }
        $this->redirect('/administration/plateforme/release-automation');
    }
}
