<?php

declare(strict_types=1);

namespace App\Services\Evidence\Sources;

use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Services\Evidence\Contracts\EvidenceSourceProvider;
use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\OperationRunOutcome;

final class OperationsSummarySource implements EvidenceSourceProvider
{
    public function key(): string
    {
        return 'operations_summary';
    }

    public function collect(ManagedEnvironment $tenant): array
    {
        $runs = OperationRun::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('created_at', '>=', now()->subDays(30))
            ->latest('created_at')
            ->get();

        $latest = $runs->max('created_at');

        return [
            'dimension_key' => $this->key(),
            'state' => $runs->isEmpty() ? EvidenceCompletenessState::Missing->value : EvidenceCompletenessState::Complete->value,
            'required' => true,
            'source_kind' => 'operation_rollup',
            'source_record_type' => OperationRun::class,
            'source_record_id' => null,
            'source_fingerprint' => hash('sha256', implode('|', $runs->pluck('run_identity_hash')->all())),
            'measured_at' => $latest,
            'freshness_at' => $latest,
            'summary_payload' => [
                'operation_count' => $runs->count(),
                'failed_count' => $runs->where('outcome', OperationRunOutcome::Failed->value)->count(),
                'partial_count' => $runs->where('outcome', OperationRunOutcome::PartiallySucceeded->value)->count(),
                'entries' => $runs->map(static fn (OperationRun $run): array => [
                    'id' => (int) $run->getKey(),
                    'type' => (string) $run->type,
                    'operation_type' => $run->canonicalOperationType(),
                    'status' => (string) $run->status,
                    'outcome' => (string) $run->outcome,
                    'initiator_name' => $run->user?->name,
                    'started_at' => $run->started_at?->toIso8601String(),
                    'completed_at' => $run->completed_at?->toIso8601String(),
                ])->all(),
            ],
            'fingerprint_payload' => [
                'count' => $runs->count(),
                'latest' => $latest?->format(DATE_ATOM),
                'hashes' => $runs->pluck('run_identity_hash')->values()->all(),
            ],
            'sort_order' => 50,
        ];
    }
}
