<?php

namespace App\Services\Moderation\Rules;

use App\Contracts\Moderation\ModerationRuleInterface;
use App\Enums\ModerationContentType;
use App\Models\ArtworkComment;

class DuplicateCommentRule implements ModerationRuleInterface
{
    public function analyze(string $content, string $normalized, array $context = []): array
    {
        if (($context['content_type'] ?? null) !== ModerationContentType::ArtworkComment->value) {
            return [];
        }

        $contentId = (int) ($context['content_id'] ?? 0);
        if ($contentId <= 0 || $normalized === '') {
            return [];
        }

        $duplicates = ArtworkComment::query()
            ->where('id', '!=', $contentId)
            ->whereNull('deleted_at')
            ->whereRaw('LOWER(TRIM(COALESCE(raw_content, content))) = ?', [$normalized])
            ->count();

        if ($duplicates < 1) {
            return [];
        }

        return [[
            'rule' => 'duplicate_comment',
            'score' => app('config')->get('content_moderation.weights.duplicate_comment', 35),
            'reason' => 'Matches ' . $duplicates . ' existing comment(s) exactly',
            'links' => [],
            'domains' => [],
            'keywords' => [],
        ]];
    }
}