<?php

namespace Tests\Feature\Api\V1\ClassProgress;

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

class ClassProgressControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_meta_returns_sections(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/class-progress/meta');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertNotEmpty($response->json('data.subject_sections'));
    }

    public function test_index_returns_paginated_reports(): void
    {
        $user = $this->createUser();
        $this->seedClassSection();
        ClassProgressReport::factory()->count(2)->create([
            'teacher_id' => $user->id,
            'class_section_id' => 101,
        ]);

        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/class-progress');

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertCount(2, $response->json('data.items'));
    }

    public function test_store_creates_reports(): void
    {
        Storage::fake('public');
        $user = $this->createUser();
        $this->seedClassSection();
        $this->assignTeacher($user->id, 101);
        Sanctum::actingAs($user);

        $payload = [
            'class_section_id' => 101,
            'week_start' => '2025-09-07',
            'week_end' => '2025-09-13',
            'covered_islamic' => 'Lesson A',
            'covered_quran' => 'Lesson B',
            'homework_islamic' => 'HW A',
            'homework_quran' => 'HW B',
            'flags' => ['needs_support'],
        ];

        $response = $this->postJson('/api/v1/class-progress', $payload);

        $response->assertStatus(201);
        $response->assertJsonPath('status', true);
        $this->assertDatabaseCount('class_progress_reports', 2);
    }

    public function test_show_returns_weekly_reports(): void
    {
        $user = $this->createUser();
        $this->seedClassSection();
        $report = ClassProgressReport::factory()->create([
            'teacher_id' => $user->id,
            'class_section_id' => 101,
            'week_start' => '2025-09-07',
            'week_end' => '2025-09-13',
            'subject' => 'Islamic Studies',
        ]);
        ClassProgressReport::factory()->create([
            'teacher_id' => $user->id,
            'class_section_id' => 101,
            'week_start' => '2025-09-07',
            'week_end' => '2025-09-13',
            'subject' => 'Quran/Arabic',
        ]);

        Sanctum::actingAs($user);

        $response = $this->getJson('/api/v1/class-progress/' . $report->id);

        $response->assertOk();
        $response->assertJsonPath('status', true);
        $this->assertCount(2, $response->json('data.weekly_reports'));
    }

    public function test_update_modifies_report(): void
    {
        $user = $this->createUser();
        $this->seedClassSection();
        $report = ClassProgressReport::factory()->create([
            'teacher_id' => $user->id,
            'class_section_id' => 101,
        ]);

        Sanctum::actingAs($user);

        $response = $this->patchJson('/api/v1/class-progress/' . $report->id, [
            'status' => 'behind',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('class_progress_reports', [
            'id' => $report->id,
            'status' => 'behind',
        ]);
    }

    public function test_destroy_deletes_report(): void
    {
        $user = $this->createUser();
        $this->seedClassSection();
        $report = ClassProgressReport::factory()->create([
            'teacher_id' => $user->id,
            'class_section_id' => 101,
        ]);

        Sanctum::actingAs($user);

        $response = $this->deleteJson('/api/v1/class-progress/' . $report->id);

        $response->assertOk();
        $this->assertDatabaseMissing('class_progress_reports', [
            'id' => $report->id,
        ]);
    }

    public function test_authorization_blocks_other_teachers(): void
    {
        $owner = $this->createUser('teacher1@example.com');
        $other = $this->createUser('teacher2@example.com');
        $this->seedClassSection();
        $report = ClassProgressReport::factory()->create([
            'teacher_id' => $owner->id,
            'class_section_id' => 101,
        ]);

        Sanctum::actingAs($other);

        $response = $this->getJson('/api/v1/class-progress/' . $report->id);

        $response->assertStatus(403);
    }

    public function test_validation_rejects_invalid_payload(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/class-progress', [
            'class_section_id' => 'invalid',
        ]);

        $response->assertStatus(422);
    }

    public function test_attachment_download_returns_file(): void
    {
        Storage::fake('public');
        Storage::disk('public')->put('class_material/sample.pdf', 'content');

        $user = $this->createUser();
        $this->seedClassSection();
        $report = ClassProgressReport::factory()->create([
            'teacher_id' => $user->id,
            'class_section_id' => 101,
        ]);
        $attachment = ClassProgressAttachment::factory()->create([
            'report_id' => $report->id,
            'file_path' => 'storage/class_material/sample.pdf',
        ]);

        Sanctum::actingAs($user);

        $response = $this->get('/api/v1/class-progress/attachments/' . $attachment->id);

        $response->assertOk();
    }

    private function seedClassSection(): void
    {
        DB::table('classSection')->insert([
            'id' => 1,
            'class_id' => 1,
            'class_section_id' => 101,
            'class_section_name' => '1-A',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);
    }

    private function assignTeacher(int $teacherId, int $classSectionId): void
    {
        DB::table('teacher_class')->insert([
            'class_section_id' => $classSectionId,
            'teacher_id' => $teacherId,
            'position' => 'main',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function createUser(string $email = 'teacher@example.com'): User
    {
        DB::table('users')->insert([
            'school_id' => 1,
            'firstname' => 'Teacher',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => $email,
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        return User::query()->where('email', $email)->firstOrFail();
    }
}
