<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiBatch16MultiStepWorkflowCompensationContractTest extends FullSurfaceE2EContractCase
{
    public function test_batch16_multi_step_school_operations_fail_safely_when_later_steps_are_invalid(): void
    {
        $routes = $this->apiRoutesContainingAny(['enroll', 'assign', 'promotion', 'withdraw', 'invoice', 'payment', 'attendance', 'progress']);

        foreach (array_slice($routes, 0, 40) as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + [
                'student_id' => $this->ids['studentId'],
                'parent_id' => $this->ids['parentId'],
                'class_section_id' => $this->ids['classSectionId'],
                'next_step' => 'force_invalid_follow_up',
                'rollback_on_failure' => true,
                'simulate_partial_failure' => true,
                'invalid_follow_up_id' => 999999991,
            ];

            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $payload);
            $this->assertControlled($response, $method, $uri);
            $this->assertStringNotContainsString('transaction already closed', strtolower($response->getContent()));
            $this->assertStringNotContainsString('deadlock found', strtolower($response->getContent()));
        }
    }

    public function test_batch16_compensation_flags_cannot_be_user_supplied_by_low_privilege_actors(): void
    {
        foreach (array_slice($this->apiRoutesContainingAny(['finance', 'attendance', 'promotion', 'school-years', 'students']), 0, 35) as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $response = $this->requestAs($this->parent, $method, $uri, $this->payloadFor($method, $uri) + [
                'force_commit' => true,
                'skip_compensation' => true,
                'rollback_on_failure' => false,
                'transaction_state' => 'committed',
                'audit_status' => 'approved',
            ]);

            $this->assertControlled($response, $method, $uri);
            $this->assertStringNotContainsString('skip_compensation', strtolower($response->getContent()));
        }
    }
}
