<?php

namespace Tests\Feature;

use App\Models\FacilityObject;
use App\Models\Location;
use App\Models\MaintenanceLog;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class InventoryFlowsTest extends TestCase
{
    use RefreshDatabase;

    public function test_guest_is_redirected_from_dashboard(): void
    {
        $this->get('/dashboard')->assertRedirect('/login');
    }

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

        $location = Location::query()->create([
            'name' => 'Kantor Tengah',
            'slug' => 'kantor-tengah',
        ]);

        $facility = FacilityObject::query()->create([
            'location_id' => $location->id,
            'name' => 'Plafon Utama',
            'slug' => 'plafon-utama',
            'qr_token' => 'qr-demo-123',
            'current_condition' => 'good',
        ]);

        $this->get('/m/qr-demo-123')->assertOk()->assertSee('Plafon Utama');

        $this->post('/m/qr-demo-123/logs', [
            'submitter_name' => 'Teknisi',
            'performed_at' => now()->toDateString(),
            'condition' => 'minor',
            'notes' => 'Perlu tindak lanjut.',
            'photo' => UploadedFile::fake()->image('bukti.jpg'),
        ])->assertRedirect('/m/qr-demo-123');

        $this->assertDatabaseHas('maintenance_logs', [
            'submitter_name' => 'Teknisi',
            'condition' => 'minor',
        ]);

        Storage::disk('public')->assertExists(MaintenanceLog::query()->first()->photo_path);

        $facility->refresh();
        $this->assertSame('minor', $facility->current_condition);
    }

    public function test_admin_can_access_dashboard(): void
    {
        $user = User::query()->create([
            'name' => 'Admin',
            'email' => 'admin@example.com',
            'is_admin' => true,
        ]);

        $this->actingAs($user)->get('/dashboard')->assertOk();
    }
}
