<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\ShippingMethod;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use Livewire\Livewire;

class ShippingMethodWeightFormTest extends TestCase
{
    use RefreshDatabase;

    private User $admin;

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

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

    /**
     * Test creating a shipping method with maximum weight in kilograms and ensuring it saves correctly in grams.
     */
    public function test_can_create_shipping_method_with_kilograms_max_weight(): void
    {
        Livewire::actingAs($this->admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        Livewire::test(\App\Filament\Resources\ShippingMethods\Pages\CreateShippingMethod::class)
            ->fillForm([
                'name' => 'Steadfast Heavy',
                'zone' => 'inside_dhaka',
                'is_active' => true,
                'pricing_type' => 'weight_based',
                'base_cost' => 60.00,
                'per_kg_rate' => 20.00,
                'max_weight_g' => 5.5, // 5.5 kg input
            ])
            ->call('create')
            ->assertHasNoFormErrors();

        $method = ShippingMethod::where('name', 'Steadfast Heavy')->first();
        $this->assertNotNull($method);
        // 5.5 kg should be stored as 5500 grams in max_weight_g
        $this->assertEquals(5500, $method->max_weight_g);
    }

    /**
     * Test editing a shipping method with max_weight_g hydrates the form in kilograms.
     */
    public function test_edit_shipping_method_hydrates_max_weight_as_kilograms(): void
    {
        $method = ShippingMethod::create([
            'name' => 'Steadfast Medium',
            'zone' => 'outside_dhaka',
            'is_active' => true,
            'pricing_type' => 'weight_based',
            'base_cost' => 100.00,
            'per_kg_rate' => 30.00,
            'max_weight_g' => 2500, // 2500 grams stored
        ]);

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

        Livewire::test(\App\Filament\Resources\ShippingMethods\Pages\EditShippingMethod::class, [
            'record' => $method->id,
        ])
            ->assertFormSet([
                'max_weight_g' => 2.5, // should display as 2.5 kg
            ]);
    }
}
