<?php

namespace App\Filament\Resources\OperationRunResource\Pages;

use App\Filament\Resources\OperationRunResource;
use App\Filament\Widgets\Operations\OperationsKpiHeader;
use App\Models\Tenant;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\ActiveRuns;
use Filament\Facades\Filament;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Database\Eloquent\Builder;

class ListOperationRuns extends ListRecords
{
    protected static string $resource = OperationRunResource::class;

    protected function getHeaderWidgets(): array
    {
        return [
            OperationsKpiHeader::class,
        ];
    }

    /**
     * @return array<string, Tab>
     */
    public function getTabs(): array
    {
        return [
            'all' => Tab::make(),
            'active' => Tab::make()
                ->modifyQueryUsing(fn (Builder $query): Builder => $query->whereIn('status', [
                    OperationRunStatus::Queued->value,
                    OperationRunStatus::Running->value,
                ])),
            'succeeded' => Tab::make()
                ->modifyQueryUsing(fn (Builder $query): Builder => $query
                    ->where('status', OperationRunStatus::Completed->value)
                    ->where('outcome', OperationRunOutcome::Succeeded->value)),
            'partial' => Tab::make()
                ->modifyQueryUsing(fn (Builder $query): Builder => $query
                    ->where('status', OperationRunStatus::Completed->value)
                    ->where('outcome', OperationRunOutcome::PartiallySucceeded->value)),
            'failed' => Tab::make()
                ->modifyQueryUsing(fn (Builder $query): Builder => $query
                    ->where('status', OperationRunStatus::Completed->value)
                    ->where('outcome', OperationRunOutcome::Failed->value)),
        ];
    }

    protected function getTablePollingInterval(): ?string
    {
        $tenant = Filament::getTenant();

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

        return ActiveRuns::existForTenant($tenant) ? '10s' : null;
    }
}
