<?php

it('validates required fields for form submission', function () {
    $response = $this->postJson('/api/v1/forms/submit', []);

    $response->assertStatus(422);
    $response->assertJsonValidationErrors([
        'formSlug',
        'responses',
        'tokenRecaptcha',
    ]);
});

it('validates formSlug is a string', function () {
    $response = $this->postJson('/api/v1/forms/submit', [
        'formSlug' => 123,
        'responses' => ['field1' => 'value1'],
        'tokenRecaptcha' => 'test-token',
    ]);

    $response->assertStatus(422);
    $response->assertJsonValidationErrors(['formSlug']);
});

it('validates responses is an array', function () {
    $response = $this->postJson('/api/v1/forms/submit', [
        'formSlug' => 'contact-form',
        'responses' => 'not-an-array',
        'tokenRecaptcha' => 'test-token',
    ]);

    $response->assertStatus(422);
    $response->assertJsonValidationErrors(['responses']);
});

it('accepts valid form submission structure', function () {
    $response = $this->postJson('/api/v1/forms/submit', [
        'formSlug' => 'contact-form',
        'responses' => [
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'message' => 'Test message',
        ],
        'tokenRecaptcha' => 'test-token',
    ]);

    // Will fail due to recaptcha or form not existing, but validation should pass
    expect($response->status())->toBeIn([200, 201, 400, 422]);
});

it('accepts nested responses array', function () {
    $response = $this->postJson('/api/v1/forms/submit', [
        'formSlug' => 'survey-form',
        'responses' => [
            'question1' => 'Answer 1',
            'question2' => ['option1', 'option2'],
            'question3' => [
                'sub1' => 'value1',
                'sub2' => 'value2',
            ],
        ],
        'tokenRecaptcha' => 'test-token',
    ]);

    // Structure is valid even if form doesn't exist
    expect($response->status())->toBeIn([200, 201, 400, 422]);
});

it('sanitizes XSS in form submissions', function () {
    $response = $this->postJson('/api/v1/forms/submit', [
        'formSlug' => '<script>alert("xss")</script>contact-form',
        'responses' => [
            'name' => '<script>alert("xss")</script>John',
        ],
        'tokenRecaptcha' => 'test-token',
    ]);

    // XSS should be sanitized, validation should still work
    expect($response->status())->toBeIn([200, 201, 400, 422]);
});

it('handles empty responses array', function () {
    $response = $this->postJson('/api/v1/forms/submit', [
        'formSlug' => 'contact-form',
        'responses' => [],
        'tokenRecaptcha' => 'test-token',
    ]);

    // Empty array might be valid depending on form configuration
    expect($response->status())->toBeIn([200, 201, 400, 422]);
});
