<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiReferentialIntegrityAndForeignKeyContractTest extends FullSurfaceE2EContractCase
{
    public function test_mutations_with_missing_foreign_keys_fail_cleanly_not_with_database_errors(): void
    {
        $foreignKeyPayload = [
            'student_id' => 99999999,
            'parent_id' => 99999999,
            'teacher_id' => 99999999,
            'class_section_id' => 99999999,
            'invoice_id' => 99999999,
            'payment_id' => 99999999,
            'school_year_id' => 99999999,
            'category_id' => 99999999,
            'item_id' => 99999999,
            'supplier_id' => 99999999,
        ];

        foreach ($this->apiRoutesContainingAny([
            'students', 'attendance', 'payments', 'refunds', 'invoices', 'inventory',
            'suppliers', 'messages', 'classes', 'teachers', 'parents', 'guardians',
        ]) as $route) {
            $method = $this->primaryMethod($route);

            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            $uri = $route->uri();
            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri) + $foreignKeyPayload);

            $this->assertStatusIn($response, [400, 403, 404, 409, 422], "{$method} {$uri} should reject impossible foreign keys cleanly.");
            $body = strtolower($response->getContent());
            $this->assertStringNotContainsString('integrity constraint violation', $body);
            $this->assertStringNotContainsString('foreign key constraint', $body);
            $this->assertStringNotContainsString('sqlstate', $body);
        }
    }

    public function test_delete_routes_for_parent_records_protect_children_or_fail_cleanly(): void
    {
        foreach ($this->apiRoutesContainingAny(['parents', 'students', 'school-years', 'classes', 'invoices', 'inventory']) as $route) {
            $method = $this->primaryMethod($route);

            if ($method !== 'DELETE') {
                continue;
            }

            $response = $this->requestAs($this->admin, 'DELETE', $route->uri());
            $this->assertStatusIn($response, [200, 202, 204, 400, 403, 404, 409, 422], "DELETE {$route->uri()} should be controlled.");

            $body = strtolower($response->getContent());
            $this->assertStringNotContainsString('constraint violation', $body);
            $this->assertStringNotContainsString('sqlstate', $body);
        }
    }
}
