<?php

namespace Tests\Feature\Api\V1\Workflows;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Concerns\AssertsE2EApiResponses;
use Tests\Concerns\SeedsE2ETestFixtures;
use Tests\TestCase;

/**
 * Scenario Z: Legacy aliases, validation contracts, and compatibility surfaces.
 *
 * This keeps old clients from silently rotting while the modern API evolves.
 * Legacy support without tests is just folklore with a URL.
 */
class ScenarioZLegacyAliasesValidationAndCompatibilityTest extends TestCase
{
    use RefreshDatabase;
    use SeedsE2ETestFixtures;
    use AssertsE2EApiResponses;

    public function test_legacy_teacher_aliases_match_modern_teacher_and_score_surfaces(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $teacher = $world['teacher'];
        $classSectionId = $world['class_section_id'];
        $this->actingAs($teacher, 'api');

        foreach ([
            '/api/v1/teacher/homework-list?class_section_id=' . $classSectionId,
            '/api/v1/teacher/add-homework?class_section_id=' . $classSectionId,
            '/api/v1/teacher/add-quiz?class_section_id=' . $classSectionId,
            '/api/v1/teacher/add-midterm-exam?class_section_id=' . $classSectionId,
            '/api/v1/teacher/add-final-exam?class_section_id=' . $classSectionId,
            '/api/v1/teacher/add-participation?class_section_id=' . $classSectionId,
            '/api/v1/teacher/add-project?class_section_id=' . $classSectionId,
            '/api/v1/teacher/teacher-assignment',
            '/api/v1/teacher/class-view?class_section_id=' . $classSectionId,
            '/api/v1/teacher/showupdate-attendance?class_section_id=' . $classSectionId,
            '/api/v1/teacher/showupdate_attendance?class_section_id=' . $classSectionId,
            '/api/v1/teacher/scores?class_section_id=' . $classSectionId,
            '/api/v1/teacher/calendar',
            '/api/v1/teacher/class-progress-submit?class_section_id=' . $classSectionId,
            '/api/v1/teacher/class-progress-history?class_section_id=' . $classSectionId,
            '/api/v1/teacher/class-progress-view?class_section_id=' . $classSectionId,
            '/api/v1/teacher/competition-scores?class_section_id=' . $classSectionId,
        ] as $endpoint) {
            $response = $this->getJson($endpoint);
            $this->assertNoServerError($response, 'Legacy teacher alias ' . $endpoint);
        }
    }

    public function test_legacy_post_aliases_validate_payloads_without_500s(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $teacher = $world['teacher'];
        $studentId = $world['student_id'];
        $classSectionId = $world['class_section_id'];
        $this->actingAs($teacher, 'api');

        $scorePayload = [
            'class_section_id' => $classSectionId,
            'school_year' => self::E2E_SCHOOL_YEAR,
            'semester' => self::E2E_SEMESTER,
            'scores' => [
                (string) $studentId => ['1' => 90],
            ],
        ];

        foreach ([
            '/api/v1/teacher/add-homework',
            '/api/v1/teacher/add-quiz',
            '/api/v1/teacher/add-midterm-exam',
            '/api/v1/teacher/add-final-exam',
            '/api/v1/teacher/add-participation',
            '/api/v1/teacher/add-project',
        ] as $endpoint) {
            $response = $this->postJson($endpoint, $scorePayload);
            $this->assertNoServerError($response, 'Legacy score post alias ' . $endpoint);
        }

        $progress = $this->postJson('/api/v1/teacher/class-progress-submit', [
            'class_section_id' => $classSectionId,
            'week_start' => '2025-10-05',
            'week_end' => '2025-10-11',
            'covered_islamic' => 'Legacy form Islamic coverage.',
            'covered_quran' => 'Legacy form Quran coverage.',
            'homework_islamic' => 'Legacy Islamic homework.',
            'homework_quran' => 'Legacy Quran homework.',
        ]);
        $this->assertNoServerError($progress, 'Legacy class progress submit');
    }

    public function test_validation_errors_are_structured_for_representative_public_and_authenticated_forms(): void
    {
        $this->seedE2EConfiguration();

        $this->postJson('/api/v1/auth/login', [
            'email' => 'not-an-email',
            'password' => '',
        ])->assertStatus(422)
            ->assertJsonStructure(['message', 'errors']);

        $this->postJson('/api/v1/contact', [
            'name' => '',
            'email' => 'bad',
            'message' => '',
        ])->assertStatus(422)
            ->assertJsonStructure(['message', 'errors']);

        $admin = $this->actingAsApiAdministrator();
        $this->actingAs($admin, 'api');

        $this->postJson('/api/v1/users', [
            'firstname' => '',
            'email' => 'not-an-email',
        ])->assertStatus(422)
            ->assertJsonStructure(['message', 'errors']);

        $this->postJson('/api/v1/students', [
            'firstname' => '',
            'parent_id' => 999999,
        ])->assertStatus(422)
            ->assertJsonStructure(['message', 'errors']);

        $this->postJson('/api/v1/finance/payments', [
            'invoice_id' => 999999,
            'amount' => -10,
        ])->assertStatus(422)
            ->assertJsonStructure(['message', 'errors']);
    }

    public function test_legacy_redirects_and_non_versioned_auth_aliases_remain_available(): void
    {
        $this->get('/api/attendance-templates')
            ->assertRedirect('/api/v1/attendance-templates');
        $this->get('/api/attendance-comment-templates')
            ->assertRedirect('/api/v1/attendance-comment-templates');
        $this->get('/api/administrator/attendance-templates')
            ->assertRedirect('/api/v1/administrator/attendance-templates');

        $this->assertStatusIn(
            $this->postJson('/api/login', [
                'email' => 'missing@example.test',
                'password' => 'wrong-password',
            ]),
            [401, 422],
            'Non-versioned login alias failure contract'
        );

        $this->postJson('/api/register', [])
            ->assertStatus(422)
            ->assertJsonStructure(['message', 'errors']);
    }
}
