<?php

namespace Tests\Feature;

use App\Modules\Core\Models\User;
use App\Modules\Inventory\Models\Product;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Models\Unit;
use App\Modules\Inventory\Models\Category;
use App\Modules\Procurement\Models\Vendor;
use App\Modules\Procurement\Models\PurchaseOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class PurchaseOrderTest extends TestCase
{
    use RefreshDatabase;

    protected $tenant;

    protected function setUp(): void
    {
        parent::setUp();
        
        // Create a unique tenant for this test run
        $tenantId = 'test_' . str_replace('.', '', microtime(true));
        
        $this->tenant = \App\Modules\Core\Models\Tenant::create([
            'id' => $tenantId,
        ]);
        
        $this->tenant->domains()->create(['domain' => $tenantId . '.test']);

        tenancy()->initialize($this->tenant);

        // Run PermissionSeeder to ensure roles/permissions exist
        $this->seed(\Database\Seeders\PermissionSeeder::class);

        // Ensure Unit exists (in Tenant DB)
        Unit::firstOrCreate(['code' => 'PC'], ['name' => 'Piece']);
    }

    protected function setupUserWithRole()
    {
        $user = User::factory()->create();
        $user->assignRole('super-admin');
        $this->actingAs($user);
        return $user;
    }

    public function test_index_hydrates_warehouse()
    {
        $user = $this->setupUserWithRole();

        $warehouse = Warehouse::create(['name' => 'Main Warehouse', 'code' => 'WH01']);
        $vendor = Vendor::create(['name' => 'Tech Corp', 'code' => 'V01']);

        PurchaseOrder::create([
            'code' => 'PO-TEST-001',
            'vendor_id' => $vendor->id,
            'warehouse_id' => $warehouse->id,
            'user_id' => $user->id,
            'status' => 'draft',
            'total_amount' => 1000,
            'tax_amount' => 50,
            'grand_total' => 1050,
            'expected_delivery_date' => now(),
        ]);

        $response = $this->get(route('purchase-orders.index'));

        $response->assertStatus(200);
        $response->assertInertia(fn ($page) => $page
            ->component('PurchaseOrder/Index')
            ->where('orders.data.0.warehouse_name', 'Main Warehouse')
        );
    }

    public function test_create_hydrates_vendor_products()
    {
        $this->setupUserWithRole();

        // Setup Data
        $vendor = Vendor::create(['name' => 'Mega Supplier', 'code' => 'V02']);
        
        $unit = Unit::first() ?? Unit::create(['name' => 'Box', 'code' => 'BX']);
        $category = Category::create(['name' => 'General', 'code' => 'GEN']);
        
        // Manual Product Creation
        $product = Product::forceCreate([
            'name' => 'Super Widget',
            'code' => 'WIDGET-01',
            'base_unit_id' => $unit->id,
            'purchase_unit_id' => $unit->id,
            'large_unit_id' => $unit->id,
            'conversion_rate' => 1,
            'category_id' => $category->id,
        ]);

        // Attach to Pivot manually (Strict Mode: no relations!)
        DB::table('product_vendor')->insert([
            'vendor_id' => $vendor->id,
            'product_id' => $product->id,
            'last_price' => 150.00,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $response = $this->get(route('purchase-orders.create'));

        $response->assertStatus(200);
        
        // Verify Hydration Logic in suppliers prop
        $response->assertInertia(fn ($page) => $page
            ->component('PurchaseOrder/Create')
            ->where('suppliers.0.name', 'Mega Supplier')
            ->has('suppliers.0.commonProducts')
            ->where('suppliers.0.commonProducts.0.productName', 'Super Widget')
            ->where('suppliers.0.commonProducts.0.lastPrice', 150) // Changed from 150.0 to 150
        );
    }
}
