<?php

declare(strict_types=1);

namespace App\Http\Controllers\News;

use App\Http\Controllers\Controller;
use App\Models\NewsArticleComment;
use App\Services\News\NewsArticleCommentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use cPad\Plugins\News\Models\NewsArticle;

final class NewsArticleCommentController extends Controller
{
    public function __construct(private readonly NewsArticleCommentService $comments)
    {
    }

    public function store(Request $request, string $slug): RedirectResponse
    {
        $article = $this->resolveArticle($slug);

        $data = $request->validate([
            'body' => ['required', 'string', 'min:2', 'max:4000'],
        ]);

        $this->comments->create($article, $request->user(), (string) $data['body']);

        return redirect()->to(route('news.show', ['slug' => $article->slug]) . '#comments')->with('status', 'Comment posted.');
    }

    public function destroy(Request $request, string $slug, NewsArticleComment $comment): RedirectResponse
    {
        $article = $this->resolveArticle($slug);

        abort_unless((int) $comment->article_id === (int) $article->id, 404);

        $this->comments->delete($comment, $request->user());

        return redirect()->to(route('news.show', ['slug' => $article->slug]) . '#comments')->with('status', 'Comment removed.');
    }

    private function resolveArticle(string $slug): NewsArticle
    {
        return NewsArticle::query()
            ->published()
            ->where('slug', $slug)
            ->firstOrFail();
    }
}