<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Operations;

use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Models\User;
use App\Services\Auth\ManagedEnvironmentAccessScopeResolver;
use App\Support\OperateHub\OperateHubShell;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\ActiveRuns;
use App\Support\Workspaces\WorkspaceContext;
use Carbon\CarbonInterval;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;

class OperationsKpiHeader extends StatsOverviewWidget
{
    protected static bool $isLazy = false;

    protected int|string|array $columnSpan = 'full';

    protected function getPollingInterval(): ?string
    {
        $tenant = $this->activeEnvironment();

        if ($tenant instanceof ManagedEnvironment) {
            return ActiveRuns::existForTenant($tenant) ? '10s' : null;
        }

        $query = $this->scopedOperationRunQuery();

        if (! $query instanceof Builder) {
            return null;
        }

        return (clone $query)
            ->whereIn('status', [
                OperationRunStatus::Queued->value,
                OperationRunStatus::Running->value,
            ])
            ->exists() ? '10s' : null;
    }

    /**
     * @return array<Stat>
     */
    protected function getStats(): array
    {
        $scopeQuery = $this->scopedOperationRunQuery();

        if (! $scopeQuery instanceof Builder) {
            return [];
        }

        $totalRuns30Days = (int) (clone $scopeQuery)
            ->where('created_at', '>=', now()->subDays(30))
            ->count();

        $activeRuns = (int) (clone $scopeQuery)
            ->whereIn('status', [
                OperationRunStatus::Queued->value,
                OperationRunStatus::Running->value,
            ])
            ->count();

        $failedOrPartial7Days = (int) (clone $scopeQuery)
            ->where('status', OperationRunStatus::Completed->value)
            ->whereIn('outcome', [
                OperationRunOutcome::Failed->value,
                OperationRunOutcome::PartiallySucceeded->value,
            ])
            ->where('completed_at', '>=', now()->subDays(7))
            ->count();

        /** @var Collection<int, OperationRun> $recentCompletedRuns */
        $recentCompletedRuns = (clone $scopeQuery)
            ->where('status', OperationRunStatus::Completed->value)
            ->whereNotNull('started_at')
            ->whereNotNull('completed_at')
            ->where('completed_at', '>=', now()->subDays(7))
            ->latest('id')
            ->limit(200)
            ->get(['started_at', 'completed_at']);

        $durations = $recentCompletedRuns
            ->map(function (OperationRun $run): ?int {
                if (! $run->started_at || ! $run->completed_at) {
                    return null;
                }

                $seconds = $run->completed_at->diffInSeconds($run->started_at);

                if (is_int($seconds)) {
                    return $seconds;
                }

                return (int) round((float) $seconds);
            })
            ->filter(fn (?int $seconds): bool => is_int($seconds) && $seconds > 0)
            ->values();

        $avgDuration7Days = '—';
        if ($durations->isNotEmpty()) {
            $avgDurationSeconds = (int) round($durations->avg() ?? 0);
            $avgDuration7Days = self::formatDurationSeconds($avgDurationSeconds);
        }

        return [
            Stat::make('Total Operations (30 days)', $totalRuns30Days),
            Stat::make('Active Operations', $activeRuns),
            Stat::make('Failed/Partial (7 days)', $failedOrPartial7Days),
            Stat::make('Avg Duration (7 days)', $avgDuration7Days),
        ];
    }

    private function activeEnvironment(): ?ManagedEnvironment
    {
        $tenant = app(OperateHubShell::class)->activeEntitledTenant(request());

        return $tenant instanceof ManagedEnvironment ? $tenant : null;
    }

    private function scopedOperationRunQuery(): ?Builder
    {
        $tenant = $this->activeEnvironment();

        if ($tenant instanceof ManagedEnvironment) {
            return OperationRun::query()
                ->where('workspace_id', (int) $tenant->workspace_id)
                ->where('managed_environment_id', (int) $tenant->getKey());
        }

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
        $user = auth()->user();

        if (! is_int($workspaceId) || ! $user instanceof User) {
            return null;
        }

        $query = OperationRun::query()
            ->where('workspace_id', $workspaceId);

        $allowedTenantIds = app(ManagedEnvironmentAccessScopeResolver::class)
            ->allowedManagedEnvironmentIdsForWorkspace($user, $workspaceId);

        if ($allowedTenantIds === null) {
            return $query;
        }

        return $query->where(function (Builder $query) use ($allowedTenantIds): void {
            $query->whereNull('managed_environment_id');

            if ($allowedTenantIds !== []) {
                $query->orWhereIn('managed_environment_id', array_values(array_unique(array_map('intval', $allowedTenantIds))));
            }
        });
    }

    private static function formatDurationSeconds(int $seconds): string
    {
        if ($seconds <= 0) {
            return '—';
        }

        if ($seconds < 60) {
            return $seconds.'s';
        }

        $interval = CarbonInterval::seconds($seconds)->cascade();

        if ($seconds < 3600) {
            return sprintf('%dm %ds', $interval->minutes, $interval->seconds);
        }

        return sprintf('%dh %dm', $interval->hours, $interval->minutes);
    }
}
