<?php

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

beforeEach(function () {
    $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(Pages\CreateProduct::class)
        ->assertFormExists()
        ->assertFormFieldExists('code');
});

it('can create a new product via livewire form', function () {
    $project = Project::factory()->create();
    
    livewire(Pages\CreateProduct::class)
        ->set('data.project_id', $project->id)
        ->set('data.product_type', 'LAND')
        ->set('data.code', 'TEST-001')
        ->set('data.area', 100)
        ->set('data.price_per_unit', 50000000)
        ->set('data.total_price', 5000000000)
        ->set('data.qsdd_value', 0)
        ->set('data.foundation_temp_value', 0)
        ->set('data.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(Pages\EditProduct::class, [
        'record' => $product->getRouteKey(),
    ])
        ->set('data.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(Pages\EditProduct::class, [
        'record' => $product->getRouteKey(),
    ])
        ->callAction(DeleteAction::class);

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