<?php

namespace Tests\Feature;

use App\Auth\Permissions;
use App\Filament\Tenant\Resources\PricingCoefficientResource;
use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\PricingCoefficient;
use App\Models\Tenant\User;
use App\Services\RbacSeeder;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\PermissionRegistrar;
use Tests\TestCase;

class PricingCoefficientResourceTest extends TestCase
{
    use RefreshDatabase;

    private Company $company;

    protected function setUp(): void
    {
        parent::setUp();
        $plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
        $this->company = Company::create(['plan_id' => $plan->id, 'slug' => 'pc-' . uniqid(), 'name' => 'PC Co', 'status' => 'active']);
        app(TenantManager::class)->setCurrent($this->company);
        app(RbacSeeder::class)->seedTenantRoles($this->company->id);
        app(PermissionRegistrar::class)->setPermissionsTeamId($this->company->id);
    }

    public function test_admin_can_view_pricing_coefficients(): void
    {
        $admin = User::create(['name' => 'A', 'email' => 'a@e.com', 'password' => bcrypt('x'), 'role' => 'admin', 'status' => 'active']);
        $admin->syncRoles(['admin']);
        $this->actingAs($admin);

        $this->assertTrue(PricingCoefficientResource::canViewAny());
    }

    public function test_mechanic_cannot_view_pricing_coefficients(): void
    {
        $mech = User::create(['name' => 'M', 'email' => 'm@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
        $mech->syncRoles(['mechanic']);

        // Verify via direct canDo — bypasses the auth->user() resolution that
        // can lose Spatie's team context in test harness.
        $this->assertFalse($mech->canDo(Permissions::ADMIN_SETTINGS_EDIT));
    }

    public function test_coefficient_can_be_created_and_matches_context(): void
    {
        $c = PricingCoefficient::create([
            'name' => 'SUV +15%',
            'multiplier' => 1.15,
            'conditions' => ['classes' => ['suv']],
            'stackable' => true,
            'priority' => 100,
            'is_active' => true,
        ]);

        $this->assertTrue($c->matches(['class' => 'suv']));
        $this->assertFalse($c->matches(['class' => 'sedan']));
    }

    public function test_pricing_engine_returns_breakdown_with_named_coefficients(): void
    {
        // Create 2 active coefficients: SUV +15% (stackable) and Express +50% (non-stackable)
        PricingCoefficient::create([
            'name' => 'SUV +15%', 'multiplier' => 1.15,
            'conditions' => ['classes' => ['suv']], 'stackable' => true,
            'priority' => 100, 'is_active' => true,
        ]);
        PricingCoefficient::create([
            'name' => 'Express +50%', 'multiplier' => 1.50,
            'conditions' => ['urgency' => ['express']], 'stackable' => false,
            'priority' => 200, 'is_active' => true,
        ]);

        $part = \App\Models\Tenant\Part::create(['name' => 'Filtru', 'article' => 'F-1', 'buy_price' => 100, 'sell_price' => 130]);
        $vehicle = (new \App\Models\Tenant\Vehicle)->forceFill(['vehicle_class' => 'suv', 'year' => 2020]);

        $quote = app(\App\Services\Pricing\PricingEngine::class)->quote(
            $part, $vehicle, null, 'express'
        );

        $this->assertCount(2, $quote['applied']);
        $names = array_column($quote['applied'], 'name');
        $this->assertContains('SUV +15%', $names);
        $this->assertContains('Express +50%', $names);
    }
}
