<?php

namespace Tests\Feature;

use App\Models\Role;
use App\Models\SchoolSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;

class SchoolSettingTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(\Database\Seeders\RoleSeeder::class);
        $this->seed(\Database\Seeders\SchoolSettingSeeder::class);
    }

    public function test_school_settings_page_can_be_rendered_by_admin(): void
    {
        $admin = User::factory()->create([
            'role_id' => Role::where('name', 'super_admin')->first()->id,
            'force_password_change' => false,
        ]);

        $response = $this->actingAs($admin)->get('/school-settings');
        $response->assertStatus(200);
    }

    public function test_admin_can_update_profile_settings(): void
    {
        $admin = User::factory()->create([
            'role_id' => Role::where('name', 'super_admin')->first()->id,
            'force_password_change' => false,
        ]);

        Livewire::actingAs($admin)
            ->test(\App\Livewire\Settings\SchoolSettingIndex::class)
            ->set('school_name', 'SMK Bisa Hebat')
            ->set('school_name_formal', 'SMK Negeri 1 Bisa Hebat')
            ->call('saveProfile')
            ->assertHasNoErrors();

        $this->assertEquals('SMK Bisa Hebat', SchoolSetting::get('school_name'));
        $this->assertEquals('SMK Negeri 1 Bisa Hebat', SchoolSetting::get('school_name_formal'));
    }

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

        $admin = User::factory()->create([
            'role_id' => Role::where('name', 'super_admin')->first()->id,
            'force_password_change' => false,
        ]);

        $file = UploadedFile::fake()->image('logo.png', 200, 200);

        Livewire::actingAs($admin)
            ->test(\App\Livewire\Settings\SchoolSettingIndex::class)
            ->set('logoFile', $file)
            ->call('uploadLogo')
            ->assertHasNoErrors();

        $path = SchoolSetting::get('school_logo');
        $this->assertNotEmpty($path);
        Storage::disk('public')->assertExists($path);
    }
}
