<?php

app_require('classes/response.php');

use classes\response;

function response_request_parameters_response_with_body(string $body): response
{
    return new class($body) extends response {
        public function __construct(private readonly string $body)
        {
        }

        protected function rawRequestBody(): string
        {
            return $this->body;
        }
    };
}

it('reads JSON payloads for DELETE request parameter arrays', function (): void {
    $previousMethod = $_SERVER['REQUEST_METHOD'] ?? null;
    $previousGet = $_GET;

    try {
        $_SERVER['REQUEST_METHOD'] = 'DELETE';
        $_GET = [];

        $response = response_request_parameters_response_with_body(json_encode([
            'confirm' => 'delete-coolify-target-3',
            'delete_resource' => false,
        ]));

        expect($response->getAllRequestParameters())->toBe([
            'confirm' => 'delete-coolify-target-3',
            'delete_resource' => false,
        ]);
        expect($response->getRequestParameter('confirm'))->toBe('delete-coolify-target-3');
        expect($response->isRequestParameterSet('delete_resource'))->toBeTrue();
    } finally {
        $_GET = $previousGet;
        if ($previousMethod === null) {
            unset($_SERVER['REQUEST_METHOD']);
        } else {
            $_SERVER['REQUEST_METHOD'] = $previousMethod;
        }
    }
});

it('keeps DELETE query parameters when no JSON body is present', function (): void {
    $previousMethod = $_SERVER['REQUEST_METHOD'] ?? null;
    $previousGet = $_GET;

    try {
        $_SERVER['REQUEST_METHOD'] = 'DELETE';
        $_GET = ['confirm' => 'delete-coolify-target-5'];

        $response = response_request_parameters_response_with_body('');

        expect($response->getAllRequestParameters())->toBe([
            'confirm' => 'delete-coolify-target-5',
        ]);
    } finally {
        $_GET = $previousGet;
        if ($previousMethod === null) {
            unset($_SERVER['REQUEST_METHOD']);
        } else {
            $_SERVER['REQUEST_METHOD'] = $previousMethod;
        }
    }
});
