<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Tenant;

use App\Models\OperationRun;
use App\Models\Tenant;
use Filament\Facades\Filament;
use Filament\Widgets\Widget;
use Illuminate\Database\Eloquent\Collection;

class RecentOperationsSummary extends Widget
{
    protected static bool $isLazy = false;

    protected string $view = 'filament.widgets.tenant.recent-operations-summary';

    public ?Tenant $record = null;

    private function resolveTenant(): ?Tenant
    {
        $tenant = Filament::getTenant();

        if ($tenant instanceof Tenant) {
            return $tenant;
        }

        return $this->record instanceof Tenant ? $this->record : null;
    }

    /**
     * @return array<string, mixed>
     */
    protected function getViewData(): array
    {
        $tenant = $this->resolveTenant();

        if (! $tenant instanceof Tenant) {
            return [
                'tenant' => null,
                'runs' => collect(),
                'operationsIndexUrl' => route('admin.operations.index'),
            ];
        }

        /** @var Collection<int, OperationRun> $runs */
        $runs = OperationRun::query()
            ->where('tenant_id', (int) $tenant->getKey())
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->limit(5)
            ->get([
                'id',
                'type',
                'status',
                'outcome',
                'created_at',
                'started_at',
                'completed_at',
            ]);

        return [
            'tenant' => $tenant,
            'runs' => $runs,
            'operationsIndexUrl' => route('admin.operations.index'),
        ];
    }
}
