<?php

namespace LaraBB\Post\UI\Web\Requests;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\HigherOrderCollectionProxy;
use LaraBB\Post\Models\Post;
use LaraBB\Post\Tasks\FindTask;
use LaraBB\Thread\Models\Thread;

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

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

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

        $this->thread = $this->post->thread;

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

        return true;
    }

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

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


    /**
     * @return RedirectResponse
     */
    public function success(): RedirectResponse
    {
        $redirectRoute = $this->thread->posts > 0 ? 'thread' : 'forum';
        $redirectParam = $this->thread->posts > 0 ? $this->thread->slug : '';

        return redirect()->route($redirectRoute, [$redirectParam])->with([
            'success' => __('The posting was deleted successfully.')
        ]);
    }

    /**
     * @return RedirectResponse
     */
    public function failed(): RedirectResponse
    {
        return redirect()->route('thread', [$this->thread->slug])->with([
            'error' => __('The posting could not be deleted due to technical difficulties.')
        ]);
    }
}
