<?php

use App\Filament\Resources\Products\ProductResource;
use App\Models\Product;
use App\Models\Project;
use App\Models\User;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\Testing\Livewire;
use Filament\Pages\Actions\DeleteAction as ActionsDeleteAction;
use function Pest\Livewire\livewire;

beforeEach(function () {
    // Tạo user và đăng nhập để qua được middleware auth của Filament
    $this->actingAs(User::factory()->create());
});

it('can render list products page', function () {
    $this->get(ProductResource::getUrl('index'))->assertStatus(200);
});

it('can render create product page and has required fields', function () {
    $this->get(ProductResource::getUrl('create'))->assertStatus(200);

    livewire(ProductResource\Pages\CreateProduct::class)
        ->assertFormExists()
        ->assertFormFieldExists('code')
        ->assertFormFieldExists('area');
});

it('can create a new product via livewire form', function () {
    $project = Project::factory()->create();
    
    livewire(ProductResource\Pages\CreateProduct::class)
        ->fillForm([
            'project_id' => $project->id,
            'product_type' => 'LAND',
            'code' => 'TEST-001',
            'area' => 100,
            'price_per_unit' => 50000000,
            'total_price' => 5000000000,
            'status' => 'Đang mở bán',
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    $this->assertDatabaseHas('products', [
        'code' => 'TEST-001',
        'area' => 100,
    ]);
});

it('can render edit page and update product data', function () {
    $product = Product::factory()->create(['code' => 'OLD-CODE']);

    $this->get(ProductResource::getUrl('edit', ['record' => $product]))->assertStatus(200);

    livewire(ProductResource\Pages\EditProduct::class, [
        'record' => $product->getRouteKey(),
    ])
        ->fillForm([
            'code' => 'NEW-CODE',
        ])
        ->call('save')
        ->assertHasNoFormErrors();

    expect($product->refresh()->code)->toBe('NEW-CODE');
});

it('can delete a product from edit page', function () {
    $product = Product::factory()->create();

    livewire(ProductResource\Pages\EditProduct::class, [
        'record' => $product->getRouteKey(),
    ])
        ->callAction(DeleteAction::class);

    $this->assertModelMissing($product);
});
