<?php

declare(strict_types=1);

namespace App\Services\EnvironmentReviews;

use App\Models\EvidenceSnapshot;
use App\Models\ReviewPack;
use App\Models\ManagedEnvironment;
use App\Models\EnvironmentReview;
use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger;
use App\Support\Audit\AuditActionId;
use App\Support\EnvironmentReviewStatus;
use App\Support\Ui\DerivedState\DerivedStateFamily;
use App\Support\Ui\DerivedState\RequestScopedDerivedStateStore;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

final class EnvironmentReviewLifecycleService
{
    public function __construct(
        private readonly EnvironmentReviewReadinessGate $readinessGate,
        private readonly EnvironmentReviewService $reviewService,
        private readonly WorkspaceAuditLogger $auditLogger,
        private readonly RequestScopedDerivedStateStore $derivedStateStore,
    ) {}

    public function publish(EnvironmentReview $review, User $user, string $reason): EnvironmentReview
    {
        $review->loadMissing(['tenant', 'sections', 'currentExportReviewPack']);
        $tenant = $review->tenant;
        $reason = $this->validatedReason($reason, 'publish_reason');

        if (! $tenant instanceof ManagedEnvironment) {
            throw new InvalidArgumentException('Review tenant could not be resolved.');
        }

        $blockers = $this->readinessGate->blockersForReview($review);
        $beforeStatus = (string) $review->status;

        if ($blockers !== []) {
            throw new InvalidArgumentException(implode(' ', $blockers));
        }

        $review->forceFill([
            'status' => EnvironmentReviewStatus::Published->value,
            'published_at' => now(),
            'published_by_user_id' => (int) $user->getKey(),
            'summary' => array_merge(is_array($review->summary) ? $review->summary : [], [
                'publish_blockers' => [],
            ]),
        ])->save();

        $this->auditLogger->log(
            workspace: $tenant->workspace,
            action: AuditActionId::EnvironmentReviewPublished,
            context: [
                'metadata' => [
                    'review_id' => (int) $review->getKey(),
                    'before_status' => $beforeStatus,
                    'after_status' => EnvironmentReviewStatus::Published->value,
                    'reason' => $reason,
                ],
            ],
            actor: $user,
            resourceType: 'environment_review',
            resourceId: (string) $review->getKey(),
            targetLabel: sprintf('ManagedEnvironment review #%d', (int) $review->getKey()),
            tenant: $tenant,
        );

        $this->invalidateArtifactTruthCache($review);

        return $review->refresh()->load(['tenant', 'sections', 'currentExportReviewPack']);
    }

    public function archive(EnvironmentReview $review, User $user, string $reason): EnvironmentReview
    {
        $review->loadMissing('tenant');
        $tenant = $review->tenant;
        $reason = $this->validatedReason($reason, 'archive_reason');

        if (! $tenant instanceof ManagedEnvironment) {
            throw new InvalidArgumentException('Review tenant could not be resolved.');
        }

        $beforeStatus = (string) $review->status;

        if ($review->statusEnum()->isTerminal()) {
            return $review;
        }

        $review->forceFill([
            'status' => EnvironmentReviewStatus::Archived->value,
            'archived_at' => now(),
        ])->save();

        $this->auditLogger->log(
            workspace: $tenant->workspace,
            action: AuditActionId::EnvironmentReviewArchived,
            context: [
                'metadata' => [
                    'review_id' => (int) $review->getKey(),
                    'before_status' => $beforeStatus,
                    'after_status' => EnvironmentReviewStatus::Archived->value,
                    'reason' => $reason,
                ],
            ],
            actor: $user,
            resourceType: 'environment_review',
            resourceId: (string) $review->getKey(),
            targetLabel: sprintf('ManagedEnvironment review #%d', (int) $review->getKey()),
            tenant: $tenant,
        );

        $this->invalidateArtifactTruthCache($review);

        return $review->refresh()->load(['tenant', 'sections', 'currentExportReviewPack']);
    }

    public function createNextReview(EnvironmentReview $review, User $user, ?EvidenceSnapshot $snapshot = null): EnvironmentReview
    {
        $review->loadMissing(['tenant', 'evidenceSnapshot']);
        $tenant = $review->tenant;

        if (! $tenant instanceof ManagedEnvironment) {
            throw new InvalidArgumentException('Review tenant could not be resolved.');
        }

        if (! $review->isPublished()) {
            throw new InvalidArgumentException('Only published reviews can start the next cycle.');
        }

        $snapshot ??= $this->reviewService->resolveLatestSnapshot($tenant) ?? $review->evidenceSnapshot;

        if (! $snapshot instanceof EvidenceSnapshot) {
            throw new InvalidArgumentException('An eligible evidence snapshot is required to create the next review.');
        }

        $nextReview = DB::transaction(function () use ($review, $user, $snapshot, $tenant): EnvironmentReview {
            $nextReview = $this->reviewService->create($tenant, $snapshot, $user);

            if ((int) $nextReview->getKey() !== (int) $review->getKey()) {
                $review->forceFill([
                    'status' => EnvironmentReviewStatus::Superseded->value,
                    'superseded_by_review_id' => (int) $nextReview->getKey(),
                ])->save();
            }

            $this->auditLogger->log(
                workspace: $tenant->workspace,
                action: AuditActionId::EnvironmentReviewSuccessorCreated,
                context: [
                    'metadata' => [
                        'review_id' => (int) $review->getKey(),
                        'next_review_id' => (int) $nextReview->getKey(),
                        'before_status' => EnvironmentReviewStatus::Published->value,
                        'after_status' => EnvironmentReviewStatus::Superseded->value,
                    ],
                ],
                actor: $user,
                resourceType: 'environment_review',
                resourceId: (string) $nextReview->getKey(),
                targetLabel: sprintf('ManagedEnvironment review #%d', (int) $nextReview->getKey()),
                tenant: $tenant,
            );

            return $nextReview->refresh()->load(['tenant', 'evidenceSnapshot', 'sections', 'operationRun', 'initiator', 'publisher']);
        });

        $this->invalidateArtifactTruthCache($review);
        $this->invalidateArtifactTruthCache($nextReview);

        return $nextReview;
    }

    private function validatedReason(mixed $reason, string $field): string
    {
        if (! is_string($reason)) {
            throw new InvalidArgumentException(sprintf('%s is required.', $field));
        }

        $resolved = trim($reason);

        if ($resolved === '') {
            throw new InvalidArgumentException(sprintf('%s is required.', $field));
        }

        if (mb_strlen($resolved) > 2000) {
            throw new InvalidArgumentException(sprintf('%s must be at most 2000 characters.', $field));
        }

        return $resolved;
    }

    private function invalidateArtifactTruthCache(EnvironmentReview $review): void
    {
        $this->derivedStateStore->invalidateModel(DerivedStateFamily::ArtifactTruth, $review, 'environment_review');

        $review->loadMissing('currentExportReviewPack');

        $pack = $review->currentExportReviewPack;

        if ($pack instanceof ReviewPack) {
            $this->derivedStateStore->invalidateModel(DerivedStateFamily::ArtifactTruth, $pack, 'review_pack');
        }
    }
}
