<?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 ScannerLookupTest extends TestCase
{
    use RefreshDatabase;

    public function test_scanner_finds_part_by_part_prefix_payload(): void
    {
        [$company, $part] = $this->makePart('FA-001');

        // Simulate the controller-level lookup logic (Scanner::resolveAndRedirect).
        $code = 'PART:FA-001';
        $clean = str_starts_with($code, 'PART:') ? substr($code, 5) : $code;

        $found = Part::where(function ($q) use ($clean) {
            $q->where('article', $clean)->orWhere('barcode', $clean);
            if (ctype_digit($clean)) $q->orWhere('id', (int) $clean);
        })->first();

        $this->assertNotNull($found);
        $this->assertEquals($part->id, $found->id);
    }

    public function test_scanner_finds_part_by_raw_barcode(): void
    {
        [$company, $part] = $this->makePart('FA-002', '4607177921365');

        $code = '4607177921365';
        $found = Part::where('barcode', $code)->orWhere('article', $code)->first();
        $this->assertNotNull($found);
        $this->assertEquals($part->id, $found->id);
    }

    public function test_scanner_misses_for_unknown_code(): void
    {
        $this->makePart('FA-003');

        $found = Part::where('article', 'GHOST-999')->orWhere('barcode', 'GHOST-999')->first();
        $this->assertNull($found);
    }

    private function makePart(string $article, ?string $barcode = null): array
    {
        $plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
        $company = Company::create([
            'plan_id' => $plan->id,
            'slug' => 'sc-' . uniqid(),
            'name' => 'Scanner Service',
            'status' => 'active',
        ]);
        app(TenantManager::class)->setCurrent($company);

        $part = Part::create([
            'name' => 'Filtru ' . $article,
            'article' => $article,
            'barcode' => $barcode,
            'unit' => 'buc',
            'qty' => 0,
            'buy_price' => 0, 'sell_price' => 0,
            'is_active' => true,
        ]);

        return [$company, $part];
    }
}
