<?php

namespace App\Http\Middleware;

use Closure;
use cPad\Plugins\Forum\Services\AI\AIContentModerator;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ForumAIModerationMiddleware
{
    public function __construct(
        private readonly AIContentModerator $aiContentModerator,
    ) {
    }

    public function handle(Request $request, Closure $next, string $action = 'generic'): Response
    {
        $assessment = [
            'action' => $action,
            'ai_spam_score' => 0,
            'ai_toxicity_score' => 0,
            'flags' => [],
            'reasons' => [],
            'provider' => 'none',
            'available' => false,
            'raw' => null,
            'language' => null,
        ];

        $title = trim((string) $request->input('title', ''));
        $content = trim((string) $request->input('content', ''));
        $combinedContent = trim($title !== '' ? $title . "\n" . $content : $content);

        if (
            $combinedContent !== ''
            && (bool) config('skinbase_ai_moderation.enabled', true)
            && (bool) config('skinbase_ai_moderation.preflight.run_ai_sync', true)
        ) {
            $spamAssessment = $request->attributes->get('forum_spam_assessment');
            $assessment = ['action' => $action] + $this->aiContentModerator->analyze($combinedContent, [
                'links' => is_array($spamAssessment) ? (array) ($spamAssessment['links'] ?? []) : [],
            ]);
        }

        $request->attributes->set('forum_ai_assessment', $assessment);

        return $next($request);
    }
}