<?php

app_require('modules/selfserve/classes/selfserve_wash_flow.php');

use modules\selfserve\classes\selfserve_wash_flow;
use modules\selfserve\helpers\selfserve_task_gate_type;

it('reads machine allowed state from session summary payload safely', function (): void {
    $washFlow = file_get_contents(app_path('modules/selfserve/classes/selfserve_wash_flow.php'));

    expect($washFlow)->not->toBeFalse();

    $methodOffset = strpos($washFlow, 'public function isMachineAllowedToStartWash');
    expect($methodOffset)->not->toBeFalse();

    $methodBody = substr($washFlow, (int)$methodOffset, 300);
    expect($methodBody)->toContain("return (\$sessionSummary['session']['allowed'] ?? false) === true;");
    expect($methodBody)->not->toContain("return \$sessionSummary['allowed'] === true;");
});

it('separates session synchronization from relay hardware synchronization', function (): void {
    $washFlow = file_get_contents(app_path('modules/selfserve/classes/selfserve_wash_flow.php'));
    $interface = file_get_contents(app_path('modules/selfserve/interfaces/selfserve_wash_flow_i.php'));

    expect($washFlow)->not->toBeFalse();
    expect($interface)->not->toBeFalse();
    expect($interface)->toContain('bool $syncRelayState = true');
    expect($washFlow)->toContain('bool $syncRelayState = true');
    expect($washFlow)->toContain('if ($syncRelayState) {');
    expect($washFlow)->toContain('$this->syncMachineRelayFromVisibleServices($snapshot, $session, $activateMachine);');
    expect($washFlow)->toContain('$this->synchronizeSession($laneId, $normalizedReg, null, false, null, false);');
});

it('infers legacy-defaulted always task gates from condition_id at runtime', function (): void {
    $reflection = new ReflectionClass(selfserve_wash_flow::class);
    $flow = $reflection->newInstanceWithoutConstructor();
    $method = $reflection->getMethod('resolveTaskGate');

    $conditionGate = $method->invoke($flow, [
        'condition_id' => 22,
        'gate_type' => 'ALWAYS',
        'gate_ref_id' => null,
    ], [22, 45]);

    expect($conditionGate['gate_type'])->toBe(selfserve_task_gate_type::CONDITION);
    expect($conditionGate['gate_ref_id'])->toBe(22);

    $questionGate = $method->invoke($flow, [
        'condition_id' => 11,
        'gate_type' => 'ALWAYS',
        'gate_ref_id' => null,
    ], [22, 45]);

    expect($questionGate['gate_type'])->toBe(selfserve_task_gate_type::QUESTION);
    expect($questionGate['gate_ref_id'])->toBe(11);
});
