<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ReturnRequest;
use App\Models\ReturnRequestItem;
use App\Models\OrderHistory;
use App\Models\AuditLog;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ReturnRefundSystemTest extends TestCase
{
    use RefreshDatabase;

    private User $customer;
    private User $admin;
    private Product $product;

    protected function setUp(): void
    {
        parent::setUp();

        $this->customer = User::create([
            'name' => 'Test Customer',
            'email' => 'customer@sawdabazar.com',
            'password' => bcrypt('password123'),
            'role' => 'customer',
        ]);

        $this->admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@sawdabazar.com',
            'password' => bcrypt('password123'),
            'role' => 'admin',
        ]);

        $this->product = Product::create([
            'name' => 'Premium Shirt',
            'slug' => 'premium-shirt',
            'sku' => 'PS-001',
            'price' => 1200.00,
            'quantity' => 20,
        ]);
    }

    /**
     * Test storefront return request submission.
     */
    public function test_customer_can_submit_return_request_for_delivered_order(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-DEL-101',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $orderItem = OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
            'product_sku' => $this->product->sku,
            'price' => 1200.00,
            'quantity' => 1,
        ]);

        $this->actingAs($this->customer);

        \Livewire\Livewire::test('storefront.customer-dashboard')
            ->set('activeTab', 'orders')
            ->call('initiateReturn', $order->id)
            ->assertSet('selectedOrderForReturn.id', $order->id)
            ->set('selectedItems', [$orderItem->id => true])
            ->set('returnQuantities', [$orderItem->id => 1])
            ->set('returnType', 'refund')
            ->set('returnReason', 'wrong_item')
            ->set('refundDetails', 'bKash: 01711122233')
            ->set('customerNotes', 'Wrong size was delivered.')
            ->call('submitReturn')
            ->assertHasNoErrors()
            ->assertSet('selectedOrderForReturn', null)
            ->assertSet('activeTab', 'returns');

        // Verify request was saved
        $this->assertDatabaseHas('return_requests', [
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'status' => 'pending',
            'type' => 'refund',
            'reason' => 'wrong_item',
            'customer_notes' => 'Wrong size was delivered.',
            'refund_details' => 'bKash: 01711122233',
        ]);

        $returnRequest = ReturnRequest::first();
        $this->assertNotNull($returnRequest);

        $this->assertDatabaseHas('return_request_items', [
            'return_request_id' => $returnRequest->id,
            'order_item_id' => $orderItem->id,
            'quantity' => 1,
            'price' => 1200.00,
        ]);

        // Verify OrderHistory entry
        $this->assertDatabaseHas('order_histories', [
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'action' => 'return_requested',
            'notes' => 'Return/Refund request submitted (Request #' . $returnRequest->id . ').',
        ]);
    }

    /**
     * Test storefront return request eligibility checks.
     */
    public function test_customer_cannot_submit_return_request_for_non_delivered_orders(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-PROC-102',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'pending',
            'status' => 'processing',
        ]);

        $this->actingAs($this->customer);

        \Livewire\Livewire::test('storefront.customer-dashboard')
            ->call('initiateReturn', $order->id)
            ->assertSet('selectedOrderForReturn', null)
            ->assertDispatched('show-toast');

        $this->assertEquals(0, ReturnRequest::count());
    }

    /**
     * Test admin approve action.
     */
    public function test_admin_can_approve_return_request(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-DEL-101',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $returnRequest = ReturnRequest::create([
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'status' => 'pending',
            'type' => 'refund',
            'reason' => 'damaged',
            'refund_details' => 'bKash: 01711122233',
        ]);

        $this->actingAs($this->admin);
        
        // Assert list page loads successfully
        $response = $this->get('/admin/return-requests');
        $response->assertStatus(200);
        
        // Assert page loads successfully
        $response = $this->get('/admin/return-requests/' . $returnRequest->id . '/edit');
        $response->assertStatus(200);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\EditReturnRequest::class, [
            'record' => $returnRequest->id,
        ])
            ->callAction('approve')
            ->assertHasNoErrors();

        $this->assertEquals('approved', $returnRequest->fresh()->status);

        // Verify OrderHistory
        $this->assertDatabaseHas('order_histories', [
            'order_id' => $order->id,
            'user_id' => $this->admin->id,
            'action' => 'return_approved',
            'notes' => 'Return request #' . $returnRequest->id . ' approved by administrator.',
        ]);
    }

    /**
     * Test admin reject action.
     */
    public function test_admin_can_reject_return_request(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-DEL-101',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $returnRequest = ReturnRequest::create([
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'status' => 'pending',
            'type' => 'refund',
            'reason' => 'damaged',
            'refund_details' => 'bKash: 01711122233',
        ]);

        $this->actingAs($this->admin);
        
        $response = $this->get('/admin/return-requests/' . $returnRequest->id . '/edit');
        $response->assertStatus(200);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\EditReturnRequest::class, [
            'record' => $returnRequest->id,
        ])
            ->callAction('reject', [
                'rejection_reason' => 'Product is not damaged according to photos.',
            ])
            ->assertHasNoErrors();

        $freshRequest = $returnRequest->fresh();
        $this->assertEquals('rejected', $freshRequest->status);
        $this->assertStringContainsString('Product is not damaged', $freshRequest->admin_notes);

        // Verify OrderHistory
        $this->assertDatabaseHas('order_histories', [
            'order_id' => $order->id,
            'user_id' => $this->admin->id,
            'action' => 'return_rejected',
            'notes' => 'Return request #' . $returnRequest->id . ' rejected. Reason: Product is not damaged according to photos.',
        ]);
    }

    /**
     * Test admin complete action.
     */
    public function test_admin_can_complete_return_request(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-DEL-101',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $returnRequest = ReturnRequest::create([
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'status' => 'approved',
            'type' => 'refund',
            'reason' => 'damaged',
            'refund_details' => 'bKash: 01711122233',
        ]);

        $this->actingAs($this->admin);
        
        $response = $this->get('/admin/return-requests/' . $returnRequest->id . '/edit');
        $response->assertStatus(200);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\EditReturnRequest::class, [
            'record' => $returnRequest->id,
        ])
            ->callAction('receive_process')
            ->callAction('complete', [
                'refund_amount' => 1280.00,
                'refund_method' => 'bkash',
            ])
            ->assertHasNoErrors();

        $freshRequest = $returnRequest->fresh();
        $this->assertEquals('completed', $freshRequest->status);
        $this->assertEquals(1280.00, (float) $freshRequest->refund_amount);
        $this->assertEquals('bkash', $freshRequest->refund_method);

        // Verify order payment status updated to refunded and order status updated to returned
        $freshOrder = $order->fresh();
        $this->assertEquals('refunded', $freshOrder->payment_status);
        $this->assertEquals('returned', $freshOrder->status);

        // Verify OrderHistory
        $this->assertDatabaseHas('order_histories', [
            'order_id' => $order->id,
            'user_id' => $this->admin->id,
            'action' => 'return_completed',
            'notes' => 'Return request #' . $returnRequest->id . ' completed. Refund: ৳1,280.00 via bkash',
        ]);

        // Verify AuditLogger entry
        $this->assertDatabaseHas('audit_logs', [
            'user_id' => $this->admin->id,
            'event_type' => 'return_completed',
            'description' => 'Return request #' . $returnRequest->id . ' marked completed. Refund amount: ৳1280',
        ]);
    }

    /**
     * Test admin can load manual creation page and submit a return request.
     */
    public function test_admin_can_create_return_request_manually(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-MAN-103',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $orderItem = OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
            'product_sku' => $this->product->sku,
            'price' => 1200.00,
            'quantity' => 2,
        ]);

        $this->actingAs($this->admin);

        // Verify GET /admin/return-requests/create is 200
        $response = $this->get('/admin/return-requests/create');
        $response->assertStatus(200);

        request()->merge(['order_id' => $order->id]);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\CreateReturnRequest::class)
            ->set('data.order_id', $order->id)
            ->set('data.type', 'refund')
            ->set('data.refund_method', 'bkash')
            ->set('data.refund_amount', 1200.00)
            ->fillForm([
                'reason' => 'wrong_item',
                'refund_details' => 'bKash: 01822233344',
                'status' => 'pending',
                'customer_notes' => 'Admin manual notes',
                'items' => [
                    [
                        'order_item_id' => $orderItem->id,
                        'quantity' => 1,
                        'price' => 1200.00,
                    ]
                ],
            ])
            ->call('create')
            ->assertHasNoErrors();

        // Verify request created in database
        $this->assertDatabaseHas('return_requests', [
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'status' => 'pending',
            'type' => 'refund',
            'reason' => 'wrong_item',
            'customer_notes' => 'Admin manual notes',
            'refund_details' => 'bKash: 01822233344',
            'refund_method' => 'bkash',
            'refund_amount' => 1200.00,
        ]);

        $returnRequest = ReturnRequest::where('order_id', $order->id)->first();
        $this->assertNotNull($returnRequest);

        $this->assertDatabaseHas('return_request_items', [
            'return_request_id' => $returnRequest->id,
            'order_item_id' => $orderItem->id,
            'quantity' => 1,
            'price' => 1200.00,
        ]);

        // Verify OrderHistory
        $this->assertDatabaseHas('order_histories', [
            'order_id' => $order->id,
            'user_id' => $this->admin->id,
            'action' => 'return_requested',
            'notes' => 'Return request #' . $returnRequest->id . ' opened manually by administrator.',
        ]);
    }

    /**
     * Test admin can create return request manually for guest order (null user_id).
     */
    public function test_admin_can_create_return_request_manually_for_guest_order(): void
    {
        $order = Order::create([
            'user_id' => null,
            'order_number' => 'SB-GST-104',
            'customer_name' => 'Guest Customer',
            'customer_phone' => '01755566677',
            'shipping_address' => 'Banani, Dhaka',
            'subtotal' => 600.00,
            'shipping_cost' => 80.00,
            'grand_total' => 680.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $orderItem = OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
            'product_sku' => $this->product->sku,
            'price' => 600.00,
            'quantity' => 1,
        ]);

        $this->actingAs($this->admin);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\CreateReturnRequest::class)
            ->set('data.order_id', $order->id)
            ->set('data.type', 'refund')
            ->set('data.refund_method', 'bkash')
            ->set('data.refund_amount', 600.00)
            ->fillForm([
                'reason' => 'size_issue',
                'refund_details' => 'bKash: 01755566677',
                'status' => 'pending',
                'customer_notes' => 'Guest size issue',
                'items' => [
                    [
                        'order_item_id' => $orderItem->id,
                        'quantity' => 1,
                        'price' => 600.00,
                    ]
                ],
            ])
            ->call('create')
            ->assertHasNoErrors();

        // Verify request created in database with null user_id and correct refund method / amount
        $this->assertDatabaseHas('return_requests', [
            'order_id' => $order->id,
            'user_id' => null,
            'status' => 'pending',
            'type' => 'refund',
            'reason' => 'size_issue',
            'customer_notes' => 'Guest size issue',
            'refund_details' => 'bKash: 01755566677',
            'refund_method' => 'bkash',
            'refund_amount' => 600.00,
        ]);

        $returnRequest = ReturnRequest::where('order_id', $order->id)->first();
        $this->assertNotNull($returnRequest);

        $this->assertDatabaseHas('return_request_items', [
            'return_request_id' => $returnRequest->id,
            'order_item_id' => $orderItem->id,
            'quantity' => 1,
            'price' => 600.00,
        ]);
    }

    /**
     * Test admin can complete refund with item subtotal amount and cancel the order.
     */
    public function test_admin_can_complete_refund_using_subtotal_and_cancels_order(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-SUB-105',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $returnRequest = ReturnRequest::create([
            'order_id' => $order->id,
            'user_id' => $this->customer->id,
            'status' => 'approved',
            'type' => 'refund',
            'reason' => 'damaged',
            'refund_details' => 'bKash: 01711122233',
        ]);

        $this->actingAs($this->admin);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\EditReturnRequest::class, [
            'record' => $returnRequest->id,
        ])
            ->callAction('receive_process')
            ->callAction('complete', [
                'refund_amount' => 1200.00, // exact subtotal, less than grand_total
                'refund_method' => 'bkash',
            ])
            ->assertHasNoErrors();

        $freshRequest = $returnRequest->fresh();
        $this->assertEquals('completed', $freshRequest->status);

        $freshOrder = $order->fresh();
        $this->assertEquals('refunded', $freshOrder->payment_status);
        $this->assertEquals('returned', $freshOrder->status);
    }

    /**
     * Test admin return request form options only include delivered orders.
     */
    public function test_admin_return_request_form_options_only_include_delivered_orders(): void
    {
        // Create a delivered order
        $deliveredOrder = Order::create([
            'order_number' => 'SB-DEL-999',
            'customer_name' => 'Delivered Customer',
            'customer_phone' => '01711122233',
            'shipping_address' => 'Dhaka',
            'subtotal' => 500.00,
            'shipping_cost' => 60.00,
            'grand_total' => 560.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        // Create a processing order
        $processingOrder = Order::create([
            'order_number' => 'SB-PROC-999',
            'customer_name' => 'Processing Customer',
            'customer_phone' => '01711122234',
            'shipping_address' => 'Dhaka',
            'subtotal' => 500.00,
            'shipping_cost' => 60.00,
            'grand_total' => 560.00,
            'payment_method' => 'cod',
            'payment_status' => 'pending',
            'status' => 'processing',
        ]);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        // When creating, resolve options using CreateReturnRequest Livewire page
        $livewireCreate = \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\CreateReturnRequest::class);
        $componentCreate = $livewireCreate->instance();

        $formCreate = \Filament\Schemas\Schema::make()->livewire($componentCreate);
        $schemaCreate = \App\Filament\Resources\ReturnRequestResource::form($formCreate);
        
        $orderIdComponent = $this->findComponent($schemaCreate->getComponents(), 'order_id');
        $this->assertNotNull($orderIdComponent);
        
        $optionsCreate = $orderIdComponent->getOptions();
        
        // Delivered order should be in options, processing order should not
        $this->assertArrayHasKey($deliveredOrder->id, $optionsCreate);
        $this->assertArrayNotHasKey($processingOrder->id, $optionsCreate);

        // Create a return request for the processing order (e.g. manually or via DB)
        $returnRequest = ReturnRequest::create([
            'order_id' => $processingOrder->id,
            'user_id' => $this->customer->id,
            'status' => 'pending',
            'type' => 'refund',
            'reason' => 'damaged',
        ]);

        // When editing, resolve options using EditReturnRequest Livewire page
        $livewireEdit = \Livewire\Livewire::test(\App\Filament\Resources\ReturnRequestResource\Pages\EditReturnRequest::class, [
            'record' => $returnRequest->id,
        ]);
        $componentEdit = $livewireEdit->instance();

        $formEdit = \Filament\Schemas\Schema::make()->livewire($componentEdit)->record($componentEdit->getRecord());
        $schemaEdit = \App\Filament\Resources\ReturnRequestResource::form($formEdit);
        
        $orderIdComponentEdit = $this->findComponent($schemaEdit->getComponents(), 'order_id');
        $this->assertNotNull($orderIdComponentEdit);
        
        $optionsEdit = $orderIdComponentEdit->getOptions();
        
        // When editing, the record's associated order should be present even if not delivered
        $this->assertArrayHasKey($processingOrder->id, $optionsEdit);
        $this->assertArrayHasKey($deliveredOrder->id, $optionsEdit);
    }

    /**
     * Test admin create return request page autofills order data when order_id query param is present.
     */
    public function test_admin_create_return_request_autofills_from_query_parameter(): void
    {
        // Create a delivered order
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-AUTO-101',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        $orderItem = OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
            'product_sku' => $this->product->sku,
            'price' => 1200.00,
            'quantity' => 1,
        ]);

        $this->actingAs($this->admin);

        \Livewire\Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::withQueryParams(['order_id' => $order->id])
            ->test(\App\Filament\Resources\ReturnRequestResource\Pages\CreateReturnRequest::class)
            ->assertSet('data.order_id', (string) $order->id)
            ->assertSet('data.user_id', $this->customer->id)
            ->assertSet('data.refund_amount', 1200.00)
            ->tap(function ($livewire) use ($orderItem) {
                $items = $livewire->get('data.items');
                $this->assertCount(1, $items);
                $firstItem = reset($items);
                $this->assertEquals($orderItem->id, $firstItem['order_item_id']);
                $this->assertEquals(1, $firstItem['quantity']);
                $this->assertEquals(1200.00, (float) $firstItem['price']);
            });
    }

    /**
     * Test that the navigation badge count counts pending, approved, and processing return requests.
     */
    public function test_return_request_navigation_badge_counts_active_requests(): void
    {
        $order = Order::create([
            'user_id' => $this->customer->id,
            'order_number' => 'SB-BADGE-101',
            'customer_name' => $this->customer->name,
            'customer_phone' => '01711122233',
            'shipping_address' => 'Mirpur, Dhaka',
            'subtotal' => 1200.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1280.00,
            'payment_method' => 'cod',
            'payment_status' => 'paid',
            'status' => 'delivered',
        ]);

        // 1. Create return requests with various statuses
        ReturnRequest::create(['order_id' => $order->id, 'user_id' => $this->customer->id, 'status' => 'pending', 'type' => 'refund', 'reason' => 'damaged']);
        ReturnRequest::create(['order_id' => $order->id, 'user_id' => $this->customer->id, 'status' => 'approved', 'type' => 'refund', 'reason' => 'damaged']);
        ReturnRequest::create(['order_id' => $order->id, 'user_id' => $this->customer->id, 'status' => 'processing', 'type' => 'refund', 'reason' => 'damaged']);
        ReturnRequest::create(['order_id' => $order->id, 'user_id' => $this->customer->id, 'status' => 'completed', 'type' => 'refund', 'reason' => 'damaged']);
        ReturnRequest::create(['order_id' => $order->id, 'user_id' => $this->customer->id, 'status' => 'rejected', 'type' => 'refund', 'reason' => 'damaged']);

        // 2. Assert navigation badge count is 3 (pending, approved, processing)
        $badgeCount = \App\Filament\Resources\ReturnRequestResource::getNavigationBadge();
        $this->assertEquals('3', $badgeCount);
    }

    private function findComponent(array $components, string $name)
    {
        foreach ($components as $component) {
            if (method_exists($component, 'getName') && $component->getName() === $name) {
                return $component;
            }
            if (method_exists($component, 'getChildComponents')) {
                $found = $this->findComponent($component->getChildComponents(), $name);
                if ($found) {
                    return $found;
                }
            }
        }
        return null;
    }
}

