<?php

declare(strict_types=1);

namespace App\Services\Baselines;

use App\Jobs\CaptureBaselineSnapshotJob;
use App\Jobs\CompareBaselineToTenantJob;
use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Auth\Capabilities;
use App\Support\Baselines\BaselineFullContentRolloutGate;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;

final class BaselineEvidenceCaptureResumeService
{
    public function __construct(
        private readonly OperationRunService $runs,
        private readonly WorkspaceCapabilityResolver $workspaceCapabilities,
        private readonly BaselineFullContentRolloutGate $rolloutGate,
        private readonly AuditLogger $auditLogger,
    ) {}

    /**
     * Start a follow-up baseline capture / compare run from an existing run + resume token.
     *
     * @return array{ok: bool, run?: OperationRun, reason_code?: string}
     */
    public function resume(OperationRun $priorRun, User $initiator): array
    {
        $runType = trim((string) $priorRun->type);

        if (! in_array($runType, [OperationRunType::BaselineCapture->value, OperationRunType::BaselineCompare->value], true)) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.unsupported_run_type'];
        }

        if ($priorRun->status !== OperationRunStatus::Completed->value) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.run_not_completed'];
        }

        $tenantId = (int) ($priorRun->managed_environment_id ?? 0);

        if ($tenantId <= 0) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.missing_tenant'];
        }

        $tenant = ManagedEnvironment::query()->whereKey($tenantId)->first();

        if (! $tenant instanceof ManagedEnvironment) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.tenant_not_found'];
        }

        $workspaceId = (int) ($tenant->workspace_id ?? 0);

        if ($workspaceId <= 0) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.missing_workspace'];
        }

        $workspace = Workspace::query()->whereKey($workspaceId)->first();

        if (! $workspace instanceof Workspace) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.workspace_not_found'];
        }

        if (! $this->workspaceCapabilities->isMember($initiator, $workspace)) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.not_workspace_member'];
        }

        if (! $this->workspaceCapabilities->can($initiator, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE)) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.forbidden'];
        }

        $this->rolloutGate->assertEnabled();

        $context = is_array($priorRun->context) ? $priorRun->context : [];
        $profileId = (int) ($context['baseline_profile_id'] ?? 0);

        if ($profileId <= 0) {
            return ['ok' => false, 'reason_code' => 'baseline.resume.missing_profile'];
        }

        $resumeSection = $runType === OperationRunType::BaselineCapture->value ? 'baseline_capture' : 'baseline_compare';
        $resumeToken = data_get($context, "{$resumeSection}.resume_token");

        if (! is_string($resumeToken) || trim($resumeToken) === '') {
            return ['ok' => false, 'reason_code' => 'baseline.resume.missing_resume_token'];
        }

        $newContext = [];

        foreach (['target_scope', 'baseline_profile_id', 'baseline_snapshot_id', 'source_environment_id', 'effective_scope', 'capture_mode'] as $key) {
            if (array_key_exists($key, $context)) {
                $newContext[$key] = $context[$key];
            }
        }

        $newContext['resume_from_operation_run_id'] = (int) $priorRun->getKey();

        $newContext[$resumeSection] = [
            'resume_token' => $resumeToken,
            'resume_from_operation_run_id' => (int) $priorRun->getKey(),
        ];

        $run = $this->runs->ensureRunWithIdentity(
            tenant: $tenant,
            type: $runType,
            identityInputs: [
                'baseline_profile_id' => $profileId,
            ],
            context: $newContext,
            initiator: $initiator,
        );

        if ($run->wasRecentlyCreated) {
            match ($runType) {
                OperationRunType::BaselineCapture->value => CaptureBaselineSnapshotJob::dispatch($run),
                OperationRunType::BaselineCompare->value => CompareBaselineToTenantJob::dispatch($run),
                default => null,
            };
        }

        $this->auditLogger->log(
            tenant: $tenant,
            action: 'baseline.evidence.resume.started',
            context: [
                'metadata' => [
                    'prior_operation_run_id' => (int) $priorRun->getKey(),
                    'operation_run_id' => (int) $run->getKey(),
                    'baseline_profile_id' => $profileId,
                    'run_type' => $runType,
                ],
            ],
            actorId: (int) $initiator->getKey(),
            actorEmail: (string) $initiator->email,
            actorName: (string) $initiator->name,
            resourceType: 'operation_run',
            resourceId: (string) $priorRun->getKey(),
        );

        return ['ok' => true, 'run' => $run];
    }
}
