<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\Client;
use App\Models\Tenant\Part;
use App\Models\Tenant\Vehicle;
use App\Models\Tenant\WorkOrder;
use App\Models\Tenant\WorkOrderPart;
use App\Models\Tenant\WorkOrderWork;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class WorkOrderCalcTest extends TestCase
{
    use RefreshDatabase;

    public function test_total_recalculates_on_work_added(): void
    {
        $wo = $this->makeWorkOrder();

        WorkOrderWork::create([
            'work_order_id' => $wo->id,
            'name' => 'Schimb plăcuțe',
            'hours' => 2,
            'price_per_hour' => 400,
            'status' => 'todo',
        ]);

        $wo->refresh();
        $this->assertEquals(800.00, (float) $wo->total);
    }

    public function test_total_includes_works_plus_parts(): void
    {
        $wo = $this->makeWorkOrder();

        WorkOrderWork::create([
            'work_order_id' => $wo->id,
            'name' => 'Manoperă',
            'hours' => 1,
            'price_per_hour' => 400,
            'status' => 'todo',
        ]);

        WorkOrderPart::create([
            'work_order_id' => $wo->id,
            'name' => 'Filtru',
            'qty' => 2,
            'sell_price' => 150,
            'status' => 'needed',
        ]);

        $wo->refresh();
        $this->assertEquals(700.00, (float) $wo->total);
    }

    public function test_discount_applies_to_total(): void
    {
        $wo = $this->makeWorkOrder();
        $wo->update(['discount_pct' => 10]);

        WorkOrderWork::create([
            'work_order_id' => $wo->id,
            'name' => 'X',
            'hours' => 1,
            'price_per_hour' => 1000,
            'status' => 'todo',
        ]);

        $wo->refresh();
        $this->assertEquals(900.00, (float) $wo->total);
    }

    private function makeWorkOrder(): WorkOrder
    {
        $plan = Plan::create(['name' => 'P', 'slug' => 'p', 'price' => 0, 'features' => []]);
        $company = Company::create([
            'plan_id' => $plan->id,
            'slug' => 'wo-' . uniqid(),
            'name' => 'WO Test',
            'status' => 'active',
        ]);
        app(TenantManager::class)->setCurrent($company);

        $client = Client::create([
            'name' => 'Test', 'phone' => '+1', 'type' => 'individual', 'status' => 'active',
        ]);
        $vehicle = Vehicle::create([
            'client_id' => $client->id,
            'plate' => 'TST 001',
            'make' => 'Test',
            'model' => 'X',
        ]);

        return WorkOrder::create([
            'client_id' => $client->id,
            'vehicle_id' => $vehicle->id,
            'number' => 'WO-001',
            'opened_at' => now(),
            'status' => 'new',
            'pay_status' => 'unpaid',
            'discount_pct' => 0,
            'total' => 0,
        ]);
    }
}
