<?php

namespace App\Livewire;

use Illuminate\Support\Facades\RateLimiter;
use Livewire\Component;
use Livewire\WithPagination;

class Comments extends Component
{
    use WithPagination;

    public $model;

    public $newCommentState = [
        'body' => '',
    ];

    protected $validationAttributes = [
        'newCommentState.body' => 'comment',
    ];

    protected $listeners = [
        'refresh' => '$refresh',
    ];

    public function postComment()
    {
        $this->validate([
            'newCommentState.body' => 'required',
        ]);

        $user = auth()->user();
        $rateLimitKey = "send-comment:{$user->id}";
        $rateLimitMinutes = 60 * 5; // 5 minutes

        if (RateLimiter::tooManyAttempts($rateLimitKey, 1)) {
            $seconds = RateLimiter::availableIn($rateLimitKey);

            $this->addError('newCommentState.body', "Too many comments. Try again in {$seconds} seconds.");

            return;
        }

        RateLimiter::hit($rateLimitKey, $rateLimitMinutes);

        $comment = $this->model->comments()->make($this->newCommentState);
        $comment->user()->associate($user);
        $comment->save();

        $this->newCommentState = [
            'body' => '',
        ];

        $this->resetPage();
    }

    public function render()
    {
        $comments = $this->model
            ->comments()
            ->with('user', 'children.user', 'children.children')
            ->parent()
            ->latest()
            ->paginate(50);

        return view('livewire.comments', [
            'comments' => $comments,
        ]);
    }
}
