<?php

declare(strict_types=1);

namespace App\Support\SupportRequests;

use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\SupportDiagnostics\SupportDiagnosticBundleBuilder;

final class SupportRequestContextBuilder
{
    public const ATTACHMENT_MODE_DIAGNOSTIC_SNAPSHOT_ATTACHED = 'diagnostic_snapshot_attached';

    public const ATTACHMENT_MODE_CANONICAL_CONTEXT_ONLY = 'canonical_context_only';

    public function __construct(
        private readonly SupportDiagnosticBundleBuilder $supportDiagnosticBundleBuilder,
    ) {}

    /**
     * @return array<string, mixed>
     */
    public function forTenant(ManagedEnvironment $tenant, User $actor, bool $attachDiagnosticSnapshot): array
    {
        return $this->buildEnvelope(
            bundle: $this->supportDiagnosticBundleBuilder->forTenant($tenant, $actor),
            attachDiagnosticSnapshot: $attachDiagnosticSnapshot,
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function forOperationRun(OperationRun $run, User $actor, bool $attachDiagnosticSnapshot): array
    {
        return $this->buildEnvelope(
            bundle: $this->supportDiagnosticBundleBuilder->forOperationRun($run, $actor),
            attachDiagnosticSnapshot: $attachDiagnosticSnapshot,
        );
    }

    /**
     * @param  array<string, mixed>  $bundle
     * @return array<string, mixed>
     */
    private function buildEnvelope(array $bundle, bool $attachDiagnosticSnapshot): array
    {
        $attachmentMode = $attachDiagnosticSnapshot
            ? self::ATTACHMENT_MODE_DIAGNOSTIC_SNAPSHOT_ATTACHED
            : self::ATTACHMENT_MODE_CANONICAL_CONTEXT_ONLY;

        return [
            'schema_version' => 1,
            'generated_from' => 'support_diagnostics_bundle',
            'attachment_mode' => $attachmentMode,
            'redaction_mode' => (string) data_get($bundle, 'redaction.mode', 'default_redacted'),
            'primary_context' => [
                'type' => (string) data_get($bundle, 'context.type'),
                'workspace_id' => data_get($bundle, 'context.workspace_id'),
                'managed_environment_id' => data_get($bundle, 'context.managed_environment_id'),
                'operation_run_id' => data_get($bundle, 'context.operation_run_id'),
                'workspace_label' => data_get($bundle, 'context.workspace_label'),
                'tenant_label' => data_get($bundle, 'context.tenant_label'),
            ],
            'canonical_context' => [
                'headline' => (string) data_get($bundle, 'summary.headline', data_get($bundle, 'headline')),
                'dominant_issue' => (string) data_get($bundle, 'summary.dominant_issue', data_get($bundle, 'dominant_issue')),
                'freshness_state' => (string) data_get($bundle, 'freshness_state'),
                'completeness_note' => data_get($bundle, 'summary.completeness_note'),
                'redaction_note' => data_get($bundle, 'summary.redaction_note'),
                'context' => data_get($bundle, 'context', []),
                'tenant' => data_get($bundle, 'tenant'),
                'operation_run' => data_get($bundle, 'operation_run'),
                'sections' => $this->canonicalSections($bundle),
                'notes' => is_array($bundle['notes'] ?? null)
                    ? array_values($bundle['notes'])
                    : [],
            ],
            'diagnostic_snapshot' => $attachDiagnosticSnapshot
                ? [
                    'contextual_help' => data_get($bundle, 'contextual_help'),
                    'sections' => is_array($bundle['sections'] ?? null)
                        ? array_values($bundle['sections'])
                        : [],
                    'redaction' => is_array($bundle['redaction'] ?? null)
                        ? $bundle['redaction']
                        : [],
                    'notes' => is_array($bundle['notes'] ?? null)
                        ? array_values($bundle['notes'])
                        : [],
                ]
                : null,
            'omissions' => $attachDiagnosticSnapshot
                ? []
                : [[
                    'type' => 'diagnostic_snapshot',
                    'reason' => 'omitted_without_support_diagnostics_view',
                    'message' => 'Redacted diagnostic evidence was omitted because the creator could not view support diagnostics.',
                ]],
        ];
    }

    /**
     * @param  array<string, mixed>  $bundle
     * @return list<array<string, mixed>>
     */
    private function canonicalSections(array $bundle): array
    {
        if (! is_array($bundle['sections'] ?? null)) {
            return [];
        }

        return array_values(array_map(
            static fn (array $section): array => [
                'key' => (string) ($section['key'] ?? ''),
                'label' => (string) ($section['label'] ?? ''),
                'availability' => (string) ($section['availability'] ?? 'missing'),
                'summary' => (string) ($section['summary'] ?? ''),
                'freshness_note' => $section['freshness_note'] ?? null,
                'references' => is_array($section['references'] ?? null)
                    ? array_values($section['references'])
                    : [],
            ],
            $bundle['sections'],
        ));
    }
}
