<?php

declare(strict_types=1);

namespace App\Services\Audit;

use App\Models\OperationRun;
use App\Models\PlatformUser;
use App\Models\RestoreRun;
use App\Models\SupportRequest;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Support\Audit\AuditActionId;
use App\Support\Audit\AuditActorSnapshot;
use App\Support\Audit\AuditActorType;
use App\Support\Audit\AuditTargetSnapshot;
use Carbon\CarbonImmutable;
use InvalidArgumentException;

class WorkspaceAuditLogger
{
    public function __construct(
        private readonly AuditRecorder $auditRecorder,
    ) {}

    public function log(
        Workspace $workspace,
        string|AuditActionId $action,
        array $context = [],
        User|PlatformUser|null $actor = null,
        string $status = 'success',
        ?string $resourceType = null,
        ?string $resourceId = null,
        ?int $actorId = null,
        ?string $actorEmail = null,
        ?string $actorName = null,
        ?AuditActorType $actorType = null,
        ?string $targetLabel = null,
        ?string $summary = null,
        ?int $operationRunId = null,
        ?ManagedEnvironment $tenant = null,
    ): \App\Models\AuditLog {
        $resolvedActor = match (true) {
            $actor instanceof User => AuditActorSnapshot::human($actor),
            $actor instanceof PlatformUser => AuditActorSnapshot::platform($actor),
            default => AuditActorSnapshot::fromLegacy(
                type: $actorType ?? AuditActorType::infer($action instanceof AuditActionId ? $action->value : $action, $actorId, $actorEmail, $actorName, $context),
                id: $actorId,
                email: $actorEmail,
                label: $actorName,
            ),
        };

        return $this->auditRecorder->record(
            action: $action,
            context: $context,
            workspace: $workspace,
            tenant: $tenant,
            actor: $resolvedActor,
            target: new AuditTargetSnapshot(
                type: $resourceType,
                id: $resourceId,
                label: $targetLabel,
            ),
            outcome: $status,
            recordedAt: CarbonImmutable::now(),
            summary: $summary,
            operationRunId: $operationRunId,
        );
    }

    /**
     * @param  array<string, mixed>  $context
     */
    public function logTenantLifecycleAction(
        ManagedEnvironment $tenant,
        string|AuditActionId $action,
        array $context = [],
        User|PlatformUser|null $actor = null,
        string $status = 'success',
        ?string $summary = null,
    ): \App\Models\AuditLog {
        return $this->log(
            workspace: $tenant->workspace,
            action: $action,
            context: $context,
            actor: $actor,
            status: $status,
            resourceType: 'tenant',
            resourceId: (string) $tenant->getKey(),
            targetLabel: $tenant->name,
            summary: $summary,
            tenant: $tenant,
        );
    }

    /**
     * @param  array<string, mixed>  $bundle
     */
    public function logSupportDiagnosticsOpened(
        ManagedEnvironment $tenant,
        string $contextType,
        array $bundle,
        User|PlatformUser|null $actor = null,
        ?OperationRun $operationRun = null,
    ): \App\Models\AuditLog {
        $sectionCount = is_array($bundle['sections'] ?? null) ? count($bundle['sections']) : 0;
        $referenceCount = collect($bundle['sections'] ?? [])
            ->sum(static fn (mixed $section): int => is_array($section) && is_array($section['references'] ?? null)
                ? count($section['references'])
                : 0);

        return $this->log(
            workspace: $tenant->workspace,
            action: AuditActionId::SupportDiagnosticsOpened,
            context: [
                'context_type' => $contextType,
                'redaction_mode' => 'default_redacted',
                'section_count' => $sectionCount,
                'reference_count' => $referenceCount,
                'primary_context_id' => $operationRun instanceof OperationRun
                    ? (string) $operationRun->getKey()
                    : (string) $tenant->getKey(),
            ],
            actor: $actor,
            status: 'success',
            resourceType: 'support_diagnostic_bundle',
            resourceId: $operationRun instanceof OperationRun
                ? 'operation_run:'.$operationRun->getKey()
                : 'tenant:'.$tenant->getKey(),
            targetLabel: $operationRun instanceof OperationRun
                ? 'Support diagnostics for operation #'.$operationRun->getKey()
                : 'Support diagnostics for '.$tenant->name,
            summary: $operationRun instanceof OperationRun
                ? 'Support diagnostics opened for operation #'.$operationRun->getKey()
                : 'Support diagnostics opened for '.$tenant->name,
            operationRunId: $operationRun instanceof OperationRun ? (int) $operationRun->getKey() : null,
            tenant: $tenant,
        );
    }

    /**
     * @param  array<string, mixed>  $preflight
     */
    public function logCrossEnvironmentPromotionPreflightGenerated(
        Workspace $workspace,
        ManagedEnvironment $sourceEnvironment,
        ManagedEnvironment $targetEnvironment,
        array $preflight,
        User|PlatformUser|null $actor = null,
    ): \App\Models\AuditLog {
        $summary = is_array($preflight['summary'] ?? null) ? $preflight['summary'] : [];

        return $this->log(
            workspace: $workspace,
            action: AuditActionId::CrossEnvironmentPromotionPreflightGenerated,
            context: [
                'source_environment_id' => (int) $sourceEnvironment->getKey(),
                'source_environment_name' => (string) $sourceEnvironment->name,
                'target_environment_id' => (int) $targetEnvironment->getKey(),
                'target_environment_name' => (string) $targetEnvironment->name,
                'ready_count' => (int) ($summary['ready'] ?? 0),
                'blocked_count' => (int) ($summary['blocked'] ?? 0),
                'manual_mapping_required_count' => (int) ($summary['manual_mapping_required'] ?? 0),
                'total_count' => (int) ($summary['total'] ?? 0),
                'blocked_reason_counts' => is_array($preflight['blockedReasonCounts'] ?? null)
                    ? $preflight['blockedReasonCounts']
                    : [],
            ],
            actor: $actor,
            status: 'success',
            resourceType: 'cross_environment_promotion_preflight',
            resourceId: sprintf('%s:%s', $sourceEnvironment->getKey(), $targetEnvironment->getKey()),
            targetLabel: $sourceEnvironment->name.' -> '.$targetEnvironment->name,
            summary: 'Cross-environment promotion preflight generated for '.$sourceEnvironment->name.' -> '.$targetEnvironment->name,
        );
    }

    /**
     * @param  array<string, mixed>  $plan
     */
    public function logCrossEnvironmentPromotionExecutionQueued(
        Workspace $workspace,
        ManagedEnvironment $sourceEnvironment,
        ManagedEnvironment $targetEnvironment,
        OperationRun $operationRun,
        array $plan,
        User|PlatformUser|null $actor = null,
    ): \App\Models\AuditLog {
        $summary = is_array($plan['summary'] ?? null) ? $plan['summary'] : [];

        return $this->log(
            workspace: $workspace,
            action: AuditActionId::CrossEnvironmentPromotionExecutionQueued,
            context: [
                'source_environment_id' => (int) $sourceEnvironment->getKey(),
                'source_environment_name' => (string) $sourceEnvironment->name,
                'target_environment_id' => (int) $targetEnvironment->getKey(),
                'target_environment_name' => (string) $targetEnvironment->name,
                'selection' => is_array($plan['selection'] ?? null) ? $plan['selection'] : [],
                'ready_count' => (int) ($summary['ready'] ?? 0),
                'excluded_count' => (int) ($summary['excluded'] ?? 0),
                'created_count' => (int) ($summary['created'] ?? 0),
                'updated_count' => (int) ($summary['updated'] ?? 0),
            ],
            actor: $actor,
            status: 'queued',
            resourceType: 'operation_run',
            resourceId: (string) $operationRun->getKey(),
            targetLabel: $sourceEnvironment->name.' -> '.$targetEnvironment->name,
            summary: 'Cross-environment promotion execution queued for '.$sourceEnvironment->name.' -> '.$targetEnvironment->name,
            operationRunId: (int) $operationRun->getKey(),
            tenant: $targetEnvironment,
        );
    }

    /**
     * @param  array<string, int>  $summaryCounts
     */
    public function logCrossEnvironmentPromotionExecutionCompleted(
        OperationRun $operationRun,
        ?int $sourceEnvironmentId,
        ManagedEnvironment $targetEnvironment,
        array $summaryCounts,
        ?RestoreRun $restoreRun = null,
    ): \App\Models\AuditLog {
        $context = is_array($operationRun->context) ? $operationRun->context : [];
        $sourceEnvironmentName = is_string($context['source_environment_name'] ?? null)
            ? (string) $context['source_environment_name']
            : null;

        return $this->log(
            workspace: $targetEnvironment->workspace,
            action: AuditActionId::CrossEnvironmentPromotionExecutionCompleted,
            context: [
                'source_environment_id' => $sourceEnvironmentId,
                'source_environment_name' => $sourceEnvironmentName,
                'target_environment_id' => (int) $targetEnvironment->getKey(),
                'target_environment_name' => (string) $targetEnvironment->name,
                'summary_counts' => $summaryCounts,
                'restore_run_id' => $restoreRun?->getKey(),
                'operation_outcome' => (string) $operationRun->outcome,
            ],
            status: match ((string) $operationRun->outcome) {
                'failed' => 'failed',
                'partially_succeeded' => 'partial',
                default => 'success',
            },
            resourceType: 'operation_run',
            resourceId: (string) $operationRun->getKey(),
            targetLabel: ($sourceEnvironmentName !== null ? $sourceEnvironmentName.' -> ' : '').$targetEnvironment->name,
            summary: 'Cross-environment promotion execution completed for '.(($sourceEnvironmentName !== null ? $sourceEnvironmentName.' -> ' : '')).$targetEnvironment->name,
            operationRunId: (int) $operationRun->getKey(),
            tenant: $targetEnvironment,
        );
    }

    public function logSupportRequestCreated(
        SupportRequest $supportRequest,
        User|PlatformUser|null $actor = null,
    ): \App\Models\AuditLog {
        $supportRequest->loadMissing(['tenant.workspace']);

        $tenant = $supportRequest->tenant;

        if (! $tenant instanceof ManagedEnvironment) {
            throw new InvalidArgumentException('Support requests must belong to a tenant.');
        }

        return $this->log(
            workspace: $tenant->workspace,
            action: AuditActionId::SupportRequestCreated,
            context: [
                'internal_reference' => $supportRequest->internal_reference,
                'primary_context_type' => $supportRequest->primary_context_type,
                'primary_context_id' => $supportRequest->primary_context_type === SupportRequest::PRIMARY_CONTEXT_OPERATION_RUN
                    ? (string) $supportRequest->operation_run_id
                    : (string) $tenant->getKey(),
                'attachment_mode' => $supportRequest->attachment_mode,
                'redaction_mode' => (string) data_get($supportRequest->context_envelope, 'redaction_mode', 'default_redacted'),
            ],
            actor: $actor,
            status: 'success',
            resourceType: 'support_request',
            resourceId: (string) $supportRequest->getKey(),
            targetLabel: $supportRequest->internal_reference,
            summary: 'Support request created for '.$supportRequest->internal_reference,
            operationRunId: $supportRequest->operation_run_id !== null ? (int) $supportRequest->operation_run_id : null,
            tenant: $tenant,
        );
    }

    public function logSupportRequestExternalTicketCreated(
        SupportRequest $supportRequest,
        User|PlatformUser|null $actor = null,
    ): \App\Models\AuditLog {
        return $this->logSupportRequestExternalHandoff(
            supportRequest: $supportRequest,
            actor: $actor,
            action: AuditActionId::SupportRequestExternalTicketCreated,
            status: 'success',
            summaryPrefix: 'External ticket created for support request ',
        );
    }

    public function logSupportRequestExternalTicketLinked(
        SupportRequest $supportRequest,
        User|PlatformUser|null $actor = null,
    ): \App\Models\AuditLog {
        return $this->logSupportRequestExternalHandoff(
            supportRequest: $supportRequest,
            actor: $actor,
            action: AuditActionId::SupportRequestExternalTicketLinked,
            status: 'success',
            summaryPrefix: 'External ticket linked for support request ',
        );
    }

    public function logSupportRequestExternalHandoffFailed(
        SupportRequest $supportRequest,
        User|PlatformUser|null $actor = null,
    ): \App\Models\AuditLog {
        return $this->logSupportRequestExternalHandoff(
            supportRequest: $supportRequest,
            actor: $actor,
            action: AuditActionId::SupportRequestExternalHandoffFailed,
            status: 'failed',
            summaryPrefix: 'External handoff failed for support request ',
        );
    }

    private function logSupportRequestExternalHandoff(
        SupportRequest $supportRequest,
        User|PlatformUser|null $actor,
        AuditActionId $action,
        string $status,
        string $summaryPrefix,
    ): \App\Models\AuditLog {
        $supportRequest->loadMissing(['tenant.workspace']);

        $tenant = $supportRequest->tenant;

        if (! $tenant instanceof ManagedEnvironment) {
            throw new InvalidArgumentException('Support requests must belong to a tenant.');
        }

        $metadata = [
            'internal_reference' => $supportRequest->internal_reference,
            'primary_context_type' => $supportRequest->primary_context_type,
            'primary_context_id' => $supportRequest->primary_context_type === SupportRequest::PRIMARY_CONTEXT_OPERATION_RUN
                ? (string) $supportRequest->operation_run_id
                : (string) $tenant->getKey(),
            'external_handoff_mode' => $supportRequest->external_handoff_mode,
            'external_ticket_reference' => $supportRequest->external_ticket_reference,
        ];

        if ($supportRequest->external_handoff_failure_summary !== null) {
            $metadata['external_handoff_failure_summary'] = $supportRequest->external_handoff_failure_summary;
        }

        return $this->log(
            workspace: $tenant->workspace,
            action: $action,
            context: $metadata,
            actor: $actor,
            status: $status,
            resourceType: 'support_request',
            resourceId: (string) $supportRequest->getKey(),
            targetLabel: $supportRequest->internal_reference,
            summary: $summaryPrefix.$supportRequest->internal_reference,
            operationRunId: $supportRequest->operation_run_id !== null ? (int) $supportRequest->operation_run_id : null,
            tenant: $tenant,
        );
    }
}
