<?php

namespace App\Services\Moderation;

use App\Models\ContentModerationDomain;
use App\Models\ContentModerationFinding;

class DomainIntelligenceService
{
    public function refreshDomain(string $domain): ?ContentModerationDomain
    {
        $record = ContentModerationDomain::query()->where('domain', $domain)->first();
        if (! $record) {
            return null;
        }

        $findings = ContentModerationFinding::query()
            ->whereJsonContains('matched_domains_json', $domain)
            ->get(['id', 'user_id', 'campaign_key', 'matched_keywords_json', 'content_type', 'is_false_positive']);

        $topKeywords = $findings
            ->flatMap(static fn (ContentModerationFinding $finding): array => (array) $finding->matched_keywords_json)
            ->filter()
            ->countBy()
            ->sortDesc()
            ->take(8)
            ->keys()
            ->values()
            ->all();

        $topContentTypes = $findings
            ->pluck('content_type')
            ->filter()
            ->countBy()
            ->sortDesc()
            ->take(8)
            ->map(static fn (int $count, string $type): array => ['type' => $type, 'count' => $count])
            ->values()
            ->all();

        $record->forceFill([
            'linked_users_count' => $findings->pluck('user_id')->filter()->unique()->count(),
            'linked_findings_count' => $findings->count(),
            'linked_clusters_count' => $findings->pluck('campaign_key')->filter()->unique()->count(),
            'top_keywords_json' => $topKeywords,
            'top_content_types_json' => $topContentTypes,
            'false_positive_count' => $findings->where('is_false_positive', true)->count(),
        ])->save();

        return $record->fresh();
    }
}