<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\Part;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class HiddenMarkupTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_internal_cost_applies_hidden_markup_percentage(): void
    {
        $part = Part::create([
            'name' => 'Filtru ulei', 'article' => 'F-001',
            'buy_price' => 61.00, 'sell_price' => 85.00,
            'hidden_markup_pct' => 39.34,
        ]);

        // 61 * (1 + 39.34/100) = 61 * 1.3934 = 85.00 (matches sell_price → margin invisible to customer)
        $this->assertEquals(85.00, $part->internalCostWithHiddenMarkup());
    }

    public function test_internal_cost_falls_back_to_buy_price_when_no_hidden_markup(): void
    {
        $part = Part::create([
            'name' => 'X', 'article' => 'X-1',
            'buy_price' => 100.00, 'sell_price' => 150.00,
        ]);

        $this->assertEquals(100.00, $part->internalCostWithHiddenMarkup());
    }

    public function test_hidden_markup_persists_through_save_reload(): void
    {
        $part = Part::create([
            'name' => 'Y', 'article' => 'Y-1',
            'buy_price' => 50, 'sell_price' => 80,
            'hidden_markup_pct' => 25.50,
        ]);
        $fresh = Part::find($part->id);
        $this->assertEquals(25.50, (float) $fresh->hidden_markup_pct);
    }
}
