<?php

namespace App\Services\Moderation\Rules;

use App\Contracts\Moderation\ModerationRuleInterface;
use App\Enums\ModerationDomainStatus;
use App\Services\Moderation\DomainReputationService;

class DomainBlacklistRule implements ModerationRuleInterface
{
    public function analyze(string $content, string $normalized, array $context = []): array
    {
        $linkRule = app(LinkPresenceRule::class);
        $urls = (array) ($context['extracted_urls'] ?? $linkRule->extractUrls($content));

        if (empty($urls)) {
            return [];
        }

        $weights = app('config')->get('content_moderation.weights', []);
        $domainService = app(DomainReputationService::class);

        $findings = [];
        $blockedMatches = [];
        $suspiciousMatches = [];

        foreach ($urls as $url) {
            $host = $linkRule->extractHost($url);
            if ($host === null) {
                continue;
            }

            $status = $domainService->statusForDomain($host);
            if ($status === ModerationDomainStatus::Blocked) {
                $blockedMatches[] = $host;
            } elseif ($status === ModerationDomainStatus::Suspicious) {
                $suspiciousMatches[] = $host;
            }
        }

        $blockedMatches = array_values(array_unique($blockedMatches));
        $suspiciousMatches = array_values(array_unique($suspiciousMatches));

        if (!empty($blockedMatches)) {
            $findings[] = [
                'rule'     => 'blocked_domain',
                'score'    => ($weights['blacklisted_domain'] ?? 70) * count($blockedMatches),
                'reason'   => 'Contains blocked domain(s): ' . implode(', ', $blockedMatches),
                'links'    => $urls,
                'domains'  => $blockedMatches,
                'keywords' => [],
            ];
        }

        if (!empty($suspiciousMatches)) {
            $findings[] = [
                'rule'     => 'suspicious_domain',
                'score'    => ($weights['suspicious_domain'] ?? 40) * count($suspiciousMatches),
                'reason'   => 'Contains suspicious TLD domain(s): ' . implode(', ', $suspiciousMatches),
                'links'    => $urls,
                'domains'  => $suspiciousMatches,
                'keywords' => [],
            ];
        }

        return $findings;
    }
}
