<?php

namespace Tests\Feature\Api\V1\Reports;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class ReportCardsControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_meta_returns_expected_payload(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $this->seedReportCardData($user->id);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/meta?school_year=2025-2026&semester=Fall');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.schoolYears'));
        $this->assertNotEmpty($response->json('data.students'));
        $this->assertArrayHasKey('id', $response->json('data.students.0'));
        $this->assertNotEmpty($response->json('data.classSections'));
        $this->assertArrayHasKey('class_section_id', $response->json('data.classSections.0'));
    }

    public function test_completeness_returns_summary_and_students(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $data = $this->seedReportCardData($user->id);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/completeness?class_section_id=' . $data['class_section_id'] . '&school_year=2025-2026&semester=Fall');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertSame(1, $response->json('data.summary.total'));
        $this->assertArrayHasKey('missing', $response->json('data.students.0'));
    }

    public function test_acknowledgement_returns_record(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $data = $this->seedReportCardData($user->id);
        $this->seedAcknowledgement($data['student_id']);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/acknowledgement?student_id=' . $data['student_id'] . '&school_year=2025-2026&semester=Fall');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $response->assertJsonPath('data.signed_name', 'Parent One');
    }

    public function test_student_report_returns_pdf(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $data = $this->seedReportCardData($user->id);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/students/' . $data['student_id'] . '?school_year=2025-2026&semester=Fall');

        $response->assertOk();
        $this->assertSame('application/pdf', $response->headers->get('content-type'));
    }

    public function test_class_report_returns_pdf(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $data = $this->seedReportCardData($user->id);

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/classes/' . $data['class_section_id'] . '?school_year=2025-2026&semester=Fall');

        $response->assertOk();
        $this->assertSame('application/pdf', $response->headers->get('content-type'));
    }

    public function test_student_report_returns_error_when_missing_scores(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();
        $data = $this->seedStudentOnly();

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/students/' . $data['student_id'] . '?school_year=2025-2026&semester=Fall');

        $response->assertStatus(422);
        $response->assertJsonPath('status', false);
    }

    public function test_completeness_requires_class_section_id(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/completeness?school_year=2025-2026');

        $response->assertStatus(422);
        $response->assertJsonPath('message', 'Validation failed.');
    }

    public function test_acknowledgement_requires_student_id(): void
    {
        $this->seedConfig();
        $user = $this->seedUser();

        Sanctum::actingAs($user);
        $response = $this->getJson('/api/v1/reports/report-cards/acknowledgement?school_year=2025-2026&semester=Fall');

        $response->assertStatus(422);
        $response->assertJsonPath('message', 'Validation failed.');
    }

    public function test_requires_authentication(): void
    {
        $response = $this->getJson('/api/v1/reports/report-cards/meta');

        $response->assertStatus(401);
    }

    private function seedConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);
    }

    private function seedUser(): User
    {
        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '9999999999',
            'email' => 'reportcards@example.com',
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);

        return User::query()->findOrFail($userId);
    }

    private function seedReportCardData(int $userId): array
    {
        DB::table('classes')->insert([
            'id' => 1,
            'class_name' => 'Grade 1',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('classSection')->insert([
            'class_section_id' => 200,
            'class_section_name' => 'Grade 1',
            'class_id' => 1,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('students')->insert([
            'id' => 100,
            'school_id' => 'SCH1',
            'firstname' => 'Student',
            'lastname' => 'One',
            'age' => 10,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => 10,
            'year_of_registration' => '2025-2026',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'is_active' => 1,
        ]);

        DB::table('student_class')->insert([
            'student_id' => 100,
            'class_section_id' => 200,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'is_event_only' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('semester_scores')->insert([
            'student_id' => 100,
            'school_id' => 'SCH1',
            'class_section_id' => 200,
            'updated_by' => $userId,
            'homework_avg' => 90,
            'quiz_avg' => 88,
            'project_avg' => 92,
            'test_avg' => 89,
            'midterm_exam_score' => 91,
            'final_exam_score' => 93,
            'attendance_score' => 95,
            'ptap_score' => 90,
            'semester_score' => 91,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return [
            'student_id' => 100,
            'class_section_id' => 200,
        ];
    }

    private function seedStudentOnly(): array
    {
        DB::table('classes')->insert([
            'id' => 2,
            'class_name' => 'Grade 2',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('classSection')->insert([
            'class_section_id' => 201,
            'class_section_name' => 'Grade 2',
            'class_id' => 2,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('students')->insert([
            'id' => 101,
            'school_id' => 'SCH2',
            'firstname' => 'Student',
            'lastname' => 'Two',
            'age' => 11,
            'gender' => 'Female',
            'photo_consent' => 1,
            'parent_id' => 11,
            'year_of_registration' => '2025-2026',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'is_active' => 1,
        ]);

        DB::table('student_class')->insert([
            'student_id' => 101,
            'class_section_id' => 201,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'is_event_only' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return [
            'student_id' => 101,
            'class_section_id' => 201,
        ];
    }

    private function seedAcknowledgement(int $studentId): void
    {
        DB::table('report_card_acknowledgements')->insert([
            'parent_id' => 10,
            'student_id' => $studentId,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'viewed_at' => now(),
            'signed_at' => now(),
            'signed_name' => 'Parent One',
            'signer_ip' => '127.0.0.1',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
