<?php

namespace App\Services\Moderation;

use App\Models\ContentModerationFinding;

class ContentModerationProcessingService
{
    public function __construct(
        private readonly ContentModerationService $moderation,
        private readonly ContentModerationPersistenceService $persistence,
        private readonly DomainReputationService $domains,
        private readonly ModerationClusterService $clusters,
        private readonly DomainIntelligenceService $domainIntelligence,
    ) {
    }

    /**
     * @param array<string, mixed> $context
     * @return array{result:\App\Data\Moderation\ModerationResultData,finding:?ContentModerationFinding,created:bool,updated:bool,auto_hidden:bool}
     */
    public function process(string $content, array $context, bool $persist = true): array
    {
        $result = $this->moderation->analyze($content, $context);
        $this->domains->trackDomains(
            $result->matchedDomains,
            $this->persistence->shouldQueue($result),
            false,
        );

        if (! $persist) {
            return [
                'result' => $result,
                'finding' => null,
                'created' => false,
                'updated' => false,
                'auto_hidden' => false,
            ];
        }

        $persisted = $this->persistence->persist($result, $context);
        $finding = $persisted['finding'];

        if ($finding !== null) {
            $this->domains->attachDomainIds($finding);
            $autoHidden = $this->persistence->applyAutomatedActionIfNeeded($finding, $result, $context);
            $this->clusters->syncFinding($finding->fresh());
            foreach ($result->matchedDomains as $domain) {
                $this->domainIntelligence->refreshDomain($domain);
            }

            return [
                'result' => $result,
                'finding' => $finding->fresh(),
                'created' => $persisted['created'],
                'updated' => $persisted['updated'],
                'auto_hidden' => $autoHidden,
            ];
        }

        return [
            'result' => $result,
            'finding' => null,
            'created' => false,
            'updated' => false,
            'auto_hidden' => false,
        ];
    }

    public function rescanFinding(ContentModerationFinding $finding, ContentModerationSourceService $sources): ?ContentModerationFinding
    {
        $resolved = $sources->contextForFinding($finding);
        if ($resolved['context'] === null) {
            return null;
        }

        $result = $this->process((string) $resolved['context']['content_snapshot'], $resolved['context'], true);

        return $result['finding'];
    }
}