<?php

namespace App\Services\Drift;

use App\Models\InventorySyncRun;
use App\Models\Tenant;

class DriftRunSelector
{
    /**
     * @return array{baseline:InventorySyncRun,current:InventorySyncRun}|null
     */
    public function selectBaselineAndCurrent(Tenant $tenant, string $scopeKey): ?array
    {
        $runs = InventorySyncRun::query()
            ->where('tenant_id', $tenant->getKey())
            ->where('selection_hash', $scopeKey)
            ->where('status', InventorySyncRun::STATUS_SUCCESS)
            ->whereNotNull('finished_at')
            ->orderByDesc('finished_at')
            ->limit(2)
            ->get();

        if ($runs->count() < 2) {
            return null;
        }

        $current = $runs->first();
        $baseline = $runs->last();

        if (! $baseline instanceof InventorySyncRun || ! $current instanceof InventorySyncRun) {
            return null;
        }

        return [
            'baseline' => $baseline,
            'current' => $current,
        ];
    }
}
