<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Illuminate\Support\Facades\DB;
use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiDatabaseTransactionRollbackContractTest extends FullSurfaceE2EContractCase
{
    public function test_multi_step_mutations_do_not_leave_obvious_partial_records_after_validation_failure(): void
    {
        $routes = $this->apiRoutesContainingAny(['students', 'users', 'finance', 'payments', 'inventory', 'reimbursements', 'families', 'guardians']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            $uri = $route->uri();
            $beforeUsers = DB::table('users')->count();
            $beforeStudents = DB::table('students')->count();

            $payload = $this->payloadFor($method, $uri) + [
                'email' => 'rollback.' . uniqid() . '@example.test',
                'firstname' => 'Rollback',
                'lastname' => 'Probe',
                'parent_id' => 999999,
                'student_id' => 999999,
                'class_section_id' => 999999,
                'force_validation_failure' => true,
            ];

            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $payload);
            $this->assertNoServerError($response, "$method $uri rollback probe");

            if (in_array($response->getStatusCode(), [400, 401, 403, 404, 409, 419, 422], true)) {
                $this->assertLessThanOrEqual($beforeUsers + 1, DB::table('users')->count(), "$uri should not spray partial user rows on failed mutation.");
                $this->assertLessThanOrEqual($beforeStudents + 1, DB::table('students')->count(), "$uri should not spray partial student rows on failed mutation.");
            }
        }
    }

    public function test_delete_failures_do_not_remove_parent_or_student_fixtures(): void
    {
        $routes = $this->apiRoutesContainingAny(['delete', 'remove', 'withdraw', 'archive']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['DELETE', 'POST', 'PATCH'], true)) {
                continue;
            }

            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), $method, $uri, ['id' => 999999, 'ids' => [999999]]);

            $this->assertNoServerError($response, "$method $uri destructive rollback");
            $this->assertNotNull(DB::table('users')->where('id', $this->parent->id)->first(), "$uri must not delete seeded parent fixture during failed destructive action.");
            $this->assertNotNull(DB::table('students')->where('id', $this->ids['studentId'])->first(), "$uri must not delete seeded student fixture during failed destructive action.");
        }
    }
}
