<?php

namespace Tests\Feature;

use App\Models\Kategori;
use App\Models\User;
use App\Models\Wisata;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class AdminWisataUploadTest extends TestCase
{
    use RefreshDatabase;

    public function test_admin_can_upload_glb_model_with_octet_stream_mime(): void
    {
        Storage::fake('public');

        $admin = User::factory()->create(['role' => 'admin']);
        $kategori = Kategori::query()->create([
            'nama' => 'Wisata Alam',
            'slug' => 'wisata-alam',
        ]);

        $this->actingAs($admin)
            ->post(route('admin.wisata.store'), [
                'kategori_id' => $kategori->id,
                'title' => 'Ranu Pani',
                'location' => 'Senduro, Lumajang',
                'rating' => 4.8,
                'image' => $this->fakePngUpload('ranu-pani.png'),
                'model_path' => UploadedFile::fake()->create('ranu-pani.glb', 128, 'application/octet-stream'),
            ])
            ->assertRedirect(route('admin.wisata.index'));

        $wisata = Wisata::query()->firstOrFail();

        $this->assertStringStartsWith('models/', $wisata->model_path);
        $this->assertStringEndsWith('.glb', $wisata->model_path);
        Storage::disk('public')->assertExists($wisata->model_path);
    }

    public function test_admin_can_upload_gltf_model(): void
    {
        Storage::fake('public');

        $admin = User::factory()->create(['role' => 'admin']);
        $kategori = Kategori::query()->create([
            'nama' => 'Wisata AR',
            'slug' => 'wisata-ar',
        ]);

        $this->actingAs($admin)
            ->post(route('admin.wisata.store'), [
                'kategori_id' => $kategori->id,
                'title' => 'Puncak B29',
                'location' => 'Argosari, Lumajang',
                'rating' => 4.7,
                'image' => $this->fakePngUpload('puncak-b29.png'),
                'model_path' => UploadedFile::fake()->create('puncak-b29.gltf', 64, 'model/gltf+json'),
            ])
            ->assertRedirect(route('admin.wisata.index'));

        $wisata = Wisata::query()->firstOrFail();

        $this->assertStringStartsWith('models/', $wisata->model_path);
        $this->assertStringEndsWith('.gltf', $wisata->model_path);
        Storage::disk('public')->assertExists($wisata->model_path);
    }

    private function fakePngUpload(string $name): UploadedFile
    {
        $path = tempnam(sys_get_temp_dir(), 'wisata-test-image-');

        file_put_contents(
            $path,
            base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=')
        );

        return new UploadedFile($path, $name, 'image/png', null, true);
    }
}
