<?php

namespace App\Jobs;

use App\Models\OperationRun;
use App\Models\Workspace;
use App\Services\Settings\SettingsResolver;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class PruneOldOperationRunsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     */
    public function handle(SettingsResolver $settingsResolver): void
    {
        $workspaceIds = OperationRun::query()
            ->whereNotNull('workspace_id')
            ->distinct()
            ->orderBy('workspace_id')
            ->pluck('workspace_id')
            ->filter(fn ($workspaceId): bool => is_numeric($workspaceId))
            ->map(fn ($workspaceId): int => (int) $workspaceId)
            ->values();

        if ($workspaceIds->isEmpty()) {
            return;
        }

        $workspaces = Workspace::query()
            ->whereIn('id', $workspaceIds->all())
            ->get()
            ->keyBy(fn (Workspace $workspace): int => (int) $workspace->getKey());

        foreach ($workspaceIds as $workspaceId) {
            $workspace = $workspaces->get($workspaceId);

            if (! $workspace instanceof Workspace) {
                continue;
            }

            $resolvedRetentionDays = $settingsResolver->resolveValue(
                workspace: $workspace,
                domain: 'operations',
                key: 'operation_run_retention_days',
            );

            $retentionDays = is_numeric($resolvedRetentionDays)
                ? max(7, min(3650, (int) $resolvedRetentionDays))
                : 90;

            OperationRun::query()
                ->where('workspace_id', $workspaceId)
                ->where('created_at', '<', now()->subDays($retentionDays))
                ->delete();
        }
    }
}
