<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\NovaCard;
use App\Models\NovaCardComment;
use App\Services\NovaCards\NovaCardCommentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class NovaCardCommentController extends Controller
{
    public function __construct(
        private readonly NovaCardCommentService $comments,
    ) {
    }

    public function store(Request $request, NovaCard $card): RedirectResponse
    {
        $this->authorize('comment', $card);

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

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

        return redirect()->to($card->publicUrl() . '#comments')->with('status', 'Comment posted.');
    }

    public function destroy(Request $request, NovaCard $card, NovaCardComment $comment): RedirectResponse
    {
        abort_unless((int) $comment->card_id === (int) $card->id, 404);

        $this->comments->delete($comment->load(['card.user']), $request->user());

        return redirect()->to($card->publicUrl() . '#comments')->with('status', 'Comment removed.');
    }
}