<?php

namespace LaraBB\Post\UI\Web\Requests;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Http\FormRequest;
use LaraBB\Post\Models\Post;
use LaraBB\Post\Tasks\FindTask;

/**
 * Class Edit
 * @package LaraBB\Post\UI\Web\Requests
 */
class Edit extends FormRequest
{
    /**
     * @var Collection|Post|mixed|null
     */
    public ?Post $post;

    /**
     * @param FindTask $getPostTask
     * @return bool
     */
    public function authorize(FindTask $getPostTask): bool
    {
        $this->post = $getPostTask->byUuid($this->route('uuid'), ['thread.forum']);

        if(is_null($this->post)) {
            abort(404, __('The posting to be edited does not exist.'));
        }

        if(!$this->user()->forumPermissions[$this->post->thread->forum_uuid]->edit_posts || $this->post->created_uuid !== $this->user()->uuid) {
            abort(403, __('You are not authorized to edit this posting.'));
        }

        return true;
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'uuid' => 'uuid'
        ];
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        return [
            'uuid.uuid' => __('The provided UUID has an incorrect format.'),
        ];
    }

    /**
     * @param null $keys
     * @return array
     */
    public function all($keys = null): array
    {
        $data         = parent::all($keys);
        $data['uuid'] = $this->route('uuid');

        return $data;
    }
}
