<?php

namespace Modules\Vrc\Tests\Unit;

use Modules\Vrc\Services\Catalog\PackageExpander;
use Modules\Vrc\Services\Contracts\TaxServiceContract;
use Modules\Vrc\Services\Finance\TotalsBuilder;
use PHPUnit\Framework\TestCase;

/**
 * §6.3 acceptance: "applying a package adds all lines with correct totals."
 * Pure unit test — PackageExpander → TotalsBuilder with a stub tax service.
 */
class PackageExpanderTest extends TestCase
{
    private function tax(): TaxServiceContract
    {
        return new class implements TaxServiceContract {
            public function percentageFor(int $businessId, ?int $taxRateId): float
            {
                return $taxRateId === 1 ? 14.0 : 0.0;
            }
        };
    }

    public function test_expand_uses_override_price_when_present(): void
    {
        $lines = (new PackageExpander)->expand([
            ['service_id' => 7, 'name' => 'Oil change', 'default_price' => 250, 'default_labor_hours' => 0.5, 'taxable' => true, 'tax_rate_id' => 1, 'qty' => 1, 'override_price' => 200],
        ]);

        $this->assertCount(1, $lines);
        $this->assertSame(200.0, $lines[0]['unit_price']);
        $this->assertSame(0.5, $lines[0]['labor_hours']);
        $this->assertSame(1, $lines[0]['tax_rate_id']);
    }

    public function test_expand_falls_back_to_default_price(): void
    {
        $lines = (new PackageExpander)->expand([
            ['service_id' => 7, 'name' => 'Oil change', 'default_price' => 250, 'taxable' => true, 'tax_rate_id' => 1, 'qty' => 2, 'override_price' => null],
        ]);

        $this->assertSame(250.0, $lines[0]['unit_price']);
        $this->assertSame(2.0, $lines[0]['qty']);
    }

    public function test_non_taxable_item_drops_tax_rate(): void
    {
        $lines = (new PackageExpander)->expand([
            ['service_id' => 9, 'name' => 'Wash', 'default_price' => 100, 'taxable' => false, 'tax_rate_id' => 1, 'qty' => 1],
        ]);

        $this->assertNull($lines[0]['tax_rate_id']);
    }

    public function test_full_package_totals(): void
    {
        $items = [
            ['service_id' => 1, 'name' => 'Oil change', 'default_price' => 250, 'default_labor_hours' => 0.5, 'taxable' => true, 'tax_rate_id' => 1, 'qty' => 1, 'override_price' => null],
            ['service_id' => 2, 'name' => 'Brake pads', 'default_price' => 400, 'default_labor_hours' => 1, 'taxable' => true, 'tax_rate_id' => 1, 'qty' => 1, 'override_price' => null],
        ];

        $lines = (new PackageExpander)->expand($items);
        $totals = (new TotalsBuilder($this->tax()))->build(1, $lines);

        // subtotal 650, tax 14% = 91, grand 741
        $this->assertSame(650.0, $totals['subtotal']);
        $this->assertSame(91.0, $totals['tax_total']);
        $this->assertSame(741.0, $totals['grand_total']);
    }
}
