<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch12GuardianDelegationExpirationContractTest extends FullSurfaceE2EContractCase
{
    public function test_guardian_and_authorized_user_routes_validate_expiration_relationship_and_scope(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['guardian', 'authorized', 'family', 'pickup', 'whatsapp']), 0, 130);
        $payloads = [
            ['expires_at' => '1900-01-01', 'relationship' => ''],
            ['expires_at' => 'not-a-date', 'relationship' => '<script>alert(1)</script>'],
            ['student_id' => $this->ids['invoiceId'], 'parent_id' => $this->ids['teacherId']],
            ['can_pickup' => 'yes please', 'can_receive_messages' => ['bad' => true]],
        ];

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

            foreach ($payloads as $payload) {
                $response = $this->requestAs($this->parent, $method, $route->uri(), $this->payloadFor($method, $route->uri()) + $payload);
                $this->assertControlled($response, $method, $route->uri());
                $this->assertNoServerError($response, 'guardian delegation '.$method.' '.$route->uri());
            }
        }
    }

    public function test_student_cannot_manage_guardians_or_authorized_users(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['guardian', 'authorized', 'family']), 0, 100);

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

            $response = $this->requestAs($this->studentUser, $method, $route->uri(), $this->payloadFor($method, $route->uri()));
            $this->assertStatusIn($response, [401, 403, 404, 405, 419, 422], 'student guardian mutation '.$method.' '.$route->uri());
            $this->assertNoServerError($response, 'student guardian mutation '.$method.' '.$route->uri());
        }
    }
}
