<?php

namespace Tests\Feature\Filament;

use App\Filament\Pages\SparkboothConnections;
use App\Models\Gallery;
use App\Models\Role;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Livewire\Livewire;
use Tests\TestCase;

class SparkboothConnectionsTest extends TestCase
{
    use DatabaseTransactions;

    public function test_admin_can_delete_connection_without_deleting_gallery(): void
    {
        $adminRole = Role::create(['name' => 'Admin']);
        Role::create(['name' => 'User']);

        $admin = User::factory()->create([
            'role_id' => $adminRole->id,
        ]);

        $this->actingAs($admin);
        Filament::setCurrentPanel('admin');

        $gallery = Gallery::factory()->create([
            'upload_enabled' => true,
            'sparkbooth_username' => 'spark-test',
            'sparkbooth_password' => 'secret-123',
        ]);

        $gallery->setUploadToken('tokentest');
        $gallery->save();

        Livewire::test(SparkboothConnections::class)
            ->callTableAction('deleteConnection', $gallery);

        $updated = $gallery->fresh();

        $this->assertDatabaseHas('galleries', ['id' => $gallery->id]);
        $this->assertNotNull($updated);
        $this->assertNull($updated->upload_token_hash);
        $this->assertNull($updated->upload_token_expires_at);
        $this->assertNull($updated->sparkbooth_username);
        $this->assertNull($updated->sparkbooth_password);
        $this->assertFalse($updated->upload_enabled);
        $this->assertSame(0, Gallery::query()->whereNotNull('upload_token_hash')->count());
    }
}
