<?php

use App\Models\InventorySyncRun;
use App\Services\Drift\DriftRunSelector;

test('it selects the previous and latest successful runs for the same scope', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');
    $this->actingAs($user);

    $scopeKey = hash('sha256', 'scope-a');

    InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDays(3),
    ]);

    $baseline = InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDays(2),
    ]);

    $current = InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDay(),
    ]);

    InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'status' => InventorySyncRun::STATUS_FAILED,
        'finished_at' => now(),
    ]);

    $selector = app(DriftRunSelector::class);

    $selected = $selector->selectBaselineAndCurrent($tenant, $scopeKey);

    expect($selected)->not->toBeNull();
    expect($selected['baseline']->getKey())->toBe($baseline->getKey());
    expect($selected['current']->getKey())->toBe($current->getKey());
});

test('it returns null when fewer than two successful runs exist for scope', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');
    $this->actingAs($user);

    $scopeKey = hash('sha256', 'scope-b');

    InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDay(),
    ]);

    $selector = app(DriftRunSelector::class);

    expect($selector->selectBaselineAndCurrent($tenant, $scopeKey))->toBeNull();
});
