<?php

namespace Tests\Feature\Integration;

use App\Models\DisciplinaryCase;
use App\Models\Student;
use App\Models\User;
use Database\Seeders\RolesAndPermissionsSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Feature\Integration\Concerns\CreatesSchoolFixtures;
use Tests\TestCase;

class LeadershipAndCaseWorkflowTest extends TestCase
{
    use CreatesSchoolFixtures;
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(RolesAndPermissionsSeeder::class);
    }

    public function test_class_teacher_can_assign_leadership_role(): void
    {
        [$year] = $this->createAcademicYearWithTerm();
        $teacherStaff = $this->createStaff();
        $teacher = $this->createTeacherUser($teacherStaff);
        $class = $this->createSchoolClass($year->id, $teacherStaff->id);
        $student = $this->createStudent();
        $class->students()->attach($student->id, ['enrolled_on' => now()->toDateString(), 'status' => 'active']);

        $this->actingAs($teacher)
            ->put(route('teacher.leadership.update', $student), ['leadership_role' => 'prefect'])
            ->assertRedirect();

        $this->assertSame('prefect', $student->fresh()->leadership_role);
    }

    public function test_head_girl_can_notify_all_students(): void
    {
        $student = $this->createStudent(['leadership_role' => 'head_girl']);
        $user = User::factory()->create(['student_id' => $student->id]);
        $user->assignRole('Student');

        $other = $this->createStudent();
        $otherUser = User::factory()->create(['student_id' => $other->id]);
        $otherUser->assignRole('Student');

        $this->actingAs($user)
            ->post(route('student.messages.store'), [
                'subject' => 'Assembly Reminder',
                'body' => 'All students must attend Friday assembly in full uniform.',
                'audience_type' => 'all_students',
            ])
            ->assertRedirect(route('student.messages.index'));

        $this->assertDatabaseHas('messages', [
            'sender_id' => $user->id,
            'subject' => 'Assembly Reminder',
            'audience_type' => 'all_students',
        ]);
    }

    public function test_regular_student_cannot_send_notifications(): void
    {
        $student = $this->createStudent(['leadership_role' => null]);
        $user = User::factory()->create(['student_id' => $student->id]);
        $user->assignRole('Student');

        $this->actingAs($user)
            ->get(route('student.messages.create'))
            ->assertForbidden();
    }

    public function test_student_can_submit_case_report(): void
    {
        [$year] = $this->createAcademicYearWithTerm();
        $teacherStaff = $this->createStaff();
        $class = $this->createSchoolClass($year->id, $teacherStaff->id);

        $reporter = $this->createStudent();
        $subject = $this->createStudent(['first_name' => 'Bad', 'last_name' => 'Actor']);
        $class->students()->attach($reporter->id, ['enrolled_on' => now()->toDateString(), 'status' => 'active']);
        $class->students()->attach($subject->id, ['enrolled_on' => now()->toDateString(), 'status' => 'active']);

        $reporterUser = User::factory()->create(['student_id' => $reporter->id]);
        $reporterUser->assignRole('Student');

        $this->actingAs($reporterUser)
            ->post(route('student.cases.store'), [
                'subject_student_id' => $subject->id,
                'title' => 'Bullying incident',
                'category' => 'bullying',
                'severity' => 'high',
                'description' => 'Repeated harassment during lunch break near the cafeteria.',
            ])
            ->assertRedirect(route('student.cases.index'));

        $this->assertDatabaseHas('disciplinary_cases', [
            'reported_by_student_id' => $reporter->id,
            'subject_student_id' => $subject->id,
            'class_teacher_id' => $teacherStaff->id,
            'stage' => 'reported',
        ]);
    }

    public function test_admin_can_finalize_case_with_suspension(): void
    {
        [$year] = $this->createAcademicYearWithTerm();
        $teacherStaff = $this->createStaff();
        $class = $this->createSchoolClass($year->id, $teacherStaff->id);
        $subject = $this->createStudent();
        $class->students()->attach($subject->id, ['enrolled_on' => now()->toDateString(), 'status' => 'active']);

        $admin = $this->createAdministrator();

        $case = DisciplinaryCase::query()->create([
            'case_number' => 'DC-2026-0099',
            'subject_student_id' => $subject->id,
            'class_id' => $class->id,
            'class_teacher_id' => $teacherStaff->id,
            'headmaster_user_id' => $admin->id,
            'title' => 'Fighting',
            'description' => 'Physical altercation on school grounds.',
            'severity' => 'critical',
            'stage' => 'decision',
            'created_by' => $admin->id,
        ]);

        $this->actingAs($admin)
            ->post(route('school.cases.advance', $case), [
                'to_stage' => 'closed',
                'outcome' => 'suspension',
                'outcome_details' => 'Two-week suspension',
                'suspension_starts_on' => now()->toDateString(),
                'suspension_ends_on' => now()->addDays(14)->toDateString(),
                'parent_notified' => '1',
                'notes' => 'Parents attended hearing.',
            ])
            ->assertRedirect();

        $case->refresh();
        $this->assertSame('closed', $case->stage);
        $this->assertSame('suspension', $case->outcome);
        $this->assertSame('suspended', $subject->fresh()->status);
        $this->assertDatabaseHas('disciplinary_records', [
            'student_id' => $subject->id,
            'disciplinary_case_id' => $case->id,
        ]);
    }
}
