<?php

namespace Tests\Feature;

use App\Filament\Resources\TenantFeedbackResource\Pages\ListTenantFeedback;
use App\Models\TenantFeedback;
use App\Models\User;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class TenantFeedbackModerationQueueTest extends TestCase
{
    use RefreshDatabase;

    public function test_superadmin_can_resolve_pending_feedback(): void
    {
        $user = User::factory()->create(['role' => 'super_admin']);
        $feedback = TenantFeedback::factory()->create(['status' => 'pending']);

        $this->bootSuperAdminPanel($user);

        Livewire::test(ListTenantFeedback::class)
            ->callAction(TestAction::make('resolve')->table($feedback), [
                'moderation_notes' => 'Handled by ops.',
            ]);

        $feedback->refresh();

        $this->assertSame('resolved', $feedback->status);
        $this->assertSame('Handled by ops.', $feedback->moderation_notes);
        $this->assertNotNull($feedback->moderated_at);
        $this->assertSame($user->id, $feedback->moderated_by);
    }

    public function test_superadmin_can_bulk_delete_feedback(): void
    {
        $user = User::factory()->create(['role' => 'super_admin']);
        $feedbackA = TenantFeedback::factory()->create(['status' => 'pending']);
        $feedbackB = TenantFeedback::factory()->create(['status' => 'pending']);

        $this->bootSuperAdminPanel($user);

        Livewire::test(ListTenantFeedback::class)
            ->callTableBulkAction('delete', [$feedbackA, $feedbackB], [
                'moderation_notes' => 'Removed due to abuse.',
            ]);

        $feedbackA->refresh();
        $feedbackB->refresh();

        $this->assertSame('deleted', $feedbackA->status);
        $this->assertSame('deleted', $feedbackB->status);
        $this->assertSame('Removed due to abuse.', $feedbackA->moderation_notes);
        $this->assertSame('Removed due to abuse.', $feedbackB->moderation_notes);
        $this->assertNotNull($feedbackA->moderated_at);
        $this->assertNotNull($feedbackB->moderated_at);
        $this->assertSame($user->id, $feedbackA->moderated_by);
        $this->assertSame($user->id, $feedbackB->moderated_by);
    }

    private function bootSuperAdminPanel(User $user): void
    {
        $panel = Filament::getPanel('superadmin');

        $this->assertNotNull($panel);

        Filament::setCurrentPanel($panel);
        Filament::bootCurrentPanel();
        Filament::auth()->login($user);
    }
}
