<?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 FilesControllerTest extends TestCase
{
    use RefreshDatabase;

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

        $dir = storage_path('uploads/receipts');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $path = $dir . DIRECTORY_SEPARATOR . 'sample.pdf';
        file_put_contents($path, 'PDFDATA');

        $response = $this->getJson('/api/v1/files/receipts/sample.pdf?meta=1');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $response->assertJsonPath('file.name', 'sample.pdf');
        $response->assertJsonPath('file.size', 7);
    }

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

        DB::table('classSection')->insert([
            'id' => 1,
            'class_section_id' => 1,
            'class_section_name' => '1A',
            'class_id' => 1,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('exam_drafts')->insert([
            'id' => 1,
            'teacher_id' => 1,
            'class_section_id' => 1,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'exam_type' => 'Midterm',
            'draft_title' => 'Draft',
            'teacher_file' => 'draft1.pdf',
            'version' => 2,
            'status' => 'draft',
        ]);

        $dir = storage_path('uploads/exams/drafts');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $path = $dir . DIRECTORY_SEPARATOR . 'draft1.pdf';
        file_put_contents($path, 'PDFDATA');

        $response = $this->get('/api/v1/files/exams/teacher/draft1.pdf');

        $response->assertOk();
        $response->assertHeader('Content-Disposition', 'inline; filename="1a_midterm_v2.pdf"');
    }

    private function seedUser(): User
    {
        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 1,
            'firstname' => 'Test',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'test@example.com',
            '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()->findOrFail(1);
    }
}
