<?php

namespace Tests\Feature\Api\V1\Workflows;

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

/**
 * Scenario Q: School-year closure and promotion lifecycle.
 *
 * This pins down the dangerous annual transition: promotion decisions, parent
 * enrollment steps, close-preview, close, reopen, and read-only protection.
 */
class ScenarioQSchoolYearPromotionClosureLifecycleTest extends TestCase
{
    use RefreshDatabase;
    use SeedsE2ETestFixtures;
    use AssertsE2EApiResponses;

    public function test_admin_and_parent_work_through_promotion_before_year_close(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $admin = $this->actingAsApiAdministrator();
        $parent = $world['parent'];
        $studentId = $world['student_id'];

        DB::table('enrollments')->insert([
            'parent_id' => $parent->id,
            'student_id' => $studentId,
            'school_year' => self::E2E_SCHOOL_YEAR,
            'semester' => self::E2E_SEMESTER,
            'enrollment_status' => 'enrolled',
            'enrollment_date' => '2025-09-01',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

        $this->getJson('/api/v1/administrator/promotions')
            ->assertOk();
        $this->getJson('/api/v1/administrator/promotions/summary')
            ->assertOk();

        $evaluate = $this->postJson('/api/v1/administrator/promotions/evaluate', [
            'school_year' => self::E2E_SCHOOL_YEAR,
            'student_ids' => [$studentId],
        ]);
        $this->assertNoServerError($evaluate, 'Promotion evaluation');

        $promotionId = (int) DB::table('student_promotion_records')
            ->where('student_id', $studentId)
            ->value('id');

        if ($promotionId > 0) {
            $this->patchJson('/api/v1/administrator/promotions/' . $promotionId . '/status', [
                'status' => 'parent_action_required',
                'decision' => 'promote',
                'notes' => 'Ready for next level.',
            ])->assertSuccessful();

            $this->actingAs($parent, 'api');
            $this->getJson('/api/v1/parents/promotions')
                ->assertOk();
            $this->postJson('/api/v1/parents/promotions/' . $promotionId . '/start')
                ->assertSuccessful();
            $this->patchJson('/api/v1/parents/promotions/' . $promotionId . '/steps', [
                'confirm_returning' => true,
                'confirm_contact_info' => true,
                'confirm_policy' => true,
            ])->assertSuccessful();
            $this->postJson('/api/v1/parents/promotions/' . $promotionId . '/submit')
                ->assertSuccessful();
        }
    }

    public function test_admin_previews_closes_and_reopens_school_year_with_balance_transfer_guardrails(): void
    {
        $world = $this->seedTeacherClassWithStudent();
        $admin = $this->actingAsApiAdministrator();
        $parentId = $world['parent_id'];
        $studentId = $world['student_id'];
        $this->seedInvoiceForParent($parentId, [
            'invoice_number' => 'INV-CLOSE-' . random_int(1000, 9999),
            'balance' => 125.00,
            'paid_amount' => 375.00,
            'total_amount' => 500.00,
            'status' => 'partial',
        ]);

        $activeYearId = (int) DB::table('school_years')
            ->where('name', self::E2E_SCHOOL_YEAR)
            ->value('id');
        $this->assertGreaterThan(0, $activeYearId);

        DB::table('enrollments')->updateOrInsert(
            ['student_id' => $studentId, 'school_year' => self::E2E_SCHOOL_YEAR],
            [
                'parent_id' => $parentId,
                'semester' => self::E2E_SEMESTER,
                'enrollment_status' => 'enrolled',
                'enrollment_date' => '2025-09-01',
                'created_at' => now(),
                'updated_at' => now(),
            ]
        );

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

        $this->postJson('/api/v1/school-years/' . $activeYearId . '/validate-close', [
            'new_school_year' => [
                'name' => '2026-2027',
                'start_date' => '2026-09-01',
                'end_date' => '2027-06-30',
            ],
            'transfer_unpaid_balances' => true,
        ])->assertSuccessful();

        $this->postJson('/api/v1/school-years/' . $activeYearId . '/preview-close', [
            'new_school_year' => [
                'name' => '2026-2027',
                'start_date' => '2026-09-01',
                'end_date' => '2027-06-30',
            ],
            'transfer_unpaid_balances' => true,
        ])->assertSuccessful();

        $close = $this->postJson('/api/v1/school-years/' . $activeYearId . '/close', [
            'new_school_year' => [
                'name' => '2026-2027',
                'start_date' => '2026-09-01',
                'end_date' => '2027-06-30',
            ],
            'transfer_unpaid_balances' => true,
            'confirmation' => 'CLOSE ' . self::E2E_SCHOOL_YEAR,
        ]);
        $this->assertNoServerError($close, 'School year close');

        $newYearId = (int) DB::table('school_years')
            ->where('name', '2026-2027')
            ->value('id');

        if ($newYearId > 0) {
            $this->postJson('/api/v1/school-years/' . $newYearId . '/reopen')
                ->assertSuccessful();
        }
    }
}
