<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Comment;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Mews\Purifier\Facades\Purifier;

class CommentController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $key = 'comment:'.$request->ip();
        if (RateLimiter::tooManyAttempts($key, 5)) {
            abort(429, 'Too many comments. Please slow down.');
        }
        RateLimiter::hit($key, 60);

        $data = $request->validate([
            'article_id' => ['required', 'integer', 'exists:articles,id'],
            'author' => ['required', 'string', 'max:50'],
            'url' => ['nullable', 'url', 'max:255'],
            'content' => ['required', 'string', 'min:2', 'max:5000'],
        ]);

        $article = Article::query()->visible()->published()->findOrFail($data['article_id']);
        if ($article->close_comment) {
            return back()->withErrors(['content' => 'Comments are closed for this article.']);
        }

        Comment::query()->create([
            'article_id' => $article->id,
            'author' => $data['author'],
            'url' => $data['url'] ?? null,
            'content' => Purifier::clean($data['content'], 'default'),
            'ip' => $request->ip(),
            'moderation_status' => Comment::STATUS_PENDING,
            'published_at' => now(),
        ]);

        $article->increment('comments_count');

        return back()->with('status', 'Comment submitted and awaiting moderation.');
    }
}
