<?php

namespace Tests\Unit\Services\Promotions;

use App\Models\StudentPromotionRecord;
use App\Services\Promotions\PromotionAuditService;
use App\Services\Promotions\PromotionEnrollmentService;
use App\Services\Promotions\PromotionStatusService;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Tests\TestCase;

class PromotionEnrollmentServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_completing_checklist_finalises_promotion_and_creates_enrollment(): void
    {
        [$record, $service, $parentId] = $this->bootstrap();

        $service->updateSteps($record, $parentId, [
            'info_confirmed' => true,
            'documents_uploaded' => true,
            'agreement_accepted' => true,
        ], $parentId);

        $service->updateSteps($record, $parentId, [
            'payment_completed' => true,
        ], $parentId);

        $record->refresh();
        $this->assertSame(StudentPromotionRecord::STATUS_PROMOTED_AND_ENROLLED, $record->promotion_status);
        $this->assertSame(StudentPromotionRecord::ENROLLMENT_COMPLETED, $record->enrollment_status);
        $this->assertNotNull($record->promotion_finalized_at);
        $this->assertDatabaseHas('enrollments', [
            'student_id' => $record->student_id,
            'school_year' => $record->next_school_year,
            'enrollment_status' => 'enrolled',
            'admission_status' => 'accepted',
        ]);
        $this->assertDatabaseHas('promotion_audit_log', [
            'promotion_id' => $record->getKey(),
            'action_type' => 'promotion_finalized',
        ]);
    }

    public function test_partial_checklist_keeps_status_in_progress(): void
    {
        [$record, $service, $parentId] = $this->bootstrap();

        $service->updateSteps($record, $parentId, [
            'info_confirmed' => true,
            'documents_uploaded' => true,
        ], $parentId);

        $record->refresh();
        $this->assertSame(StudentPromotionRecord::STATUS_ENROLLMENT_STARTED, $record->promotion_status);
        $this->assertSame(StudentPromotionRecord::ENROLLMENT_IN_PROGRESS, $record->enrollment_status);
        $this->assertNull($record->promotion_finalized_at);
    }

    public function test_submit_requires_complete_checklist(): void
    {
        [$record, $service, $parentId] = $this->bootstrap();

        $service->updateSteps($record, $parentId, [
            'info_confirmed' => true,
        ], $parentId);

        $this->expectException(RuntimeException::class);
        $service->submitEnrollment($record->refresh(), $parentId, $parentId);
    }

    public function test_other_parent_cannot_act_on_record(): void
    {
        [$record, $service] = $this->bootstrap();

        $this->expectException(RuntimeException::class);
        $service->startEnrollment($record, 9999, 9999);
    }

    public function test_expired_records_become_not_enrolled(): void
    {
        [$record, $service] = $this->bootstrap();
        $record->enrollment_deadline = now()->subDays(2)->toDateString();
        $record->save();

        $result = $service->markExpiredDeadlines(CarbonImmutable::now(), 99);

        $this->assertSame(1, $result['expired']);
        $record->refresh();
        $this->assertSame(StudentPromotionRecord::STATUS_NOT_ENROLLED, $record->promotion_status);
        $this->assertSame(StudentPromotionRecord::ENROLLMENT_EXPIRED, $record->enrollment_status);
    }

    /**
     * @return array{0:StudentPromotionRecord, 1:PromotionEnrollmentService, 2:int}
     */
    private function bootstrap(): array
    {
        $audit = new PromotionAuditService();
        $service = new PromotionEnrollmentService(new PromotionStatusService($audit), $audit);

        $parentId = (int) DB::table('users')->insertGetId([
            'firstname' => 'Parent',
            'lastname' => 'One',
            'email' => 'parent@example.com',
            'cellphone' => '5551234567',
            'address_street' => '1 Way',
            'city' => 'C',
            'state' => 'S',
            'zip' => '00000',
            'accept_school_policy' => 1,
            'password' => bcrypt('x'),
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'status' => 'Active',
        ]);

        $studentId = (int) DB::table('students')->insertGetId([
            'school_id' => 'S-1',
            'firstname' => 'Sara',
            'lastname' => 'Test',
            'parent_id' => $parentId,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        $record = StudentPromotionRecord::query()->create([
            'student_id' => $studentId,
            'parent_id' => $parentId,
            'current_school_year' => '2025-2026',
            'next_school_year' => '2026-2027',
            'promotion_status' => StudentPromotionRecord::STATUS_AWAITING_PARENT,
            'enrollment_required' => true,
            'enrollment_status' => StudentPromotionRecord::ENROLLMENT_NOT_STARTED,
            'promoted_level_name' => 'Grade 4',
            'enrollment_deadline' => now()->addDays(30)->toDateString(),
        ]);

        return [$record, $service, $parentId];
    }
}
