<?php

namespace App\Http\Requests\Dashboard;

use App\Models\Post;
use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if($this->isMethod("patch")) {
            $post = Post::find($this->route("id"));
            return auth()->user()->hasPermission("edit_all_posts") || ($post->user->id == auth()->user()->id && $post->is_confirmed);
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            "title" => "required|min:10|max:255",
            "image" => "required|mimes:jpeg,png,gif|max:5000",
            "category" => "required|integer|exists:categories,id",
            "post_content" => "required|min:100",
            "tags" => "required"
        ];

        if($this->isMethod("patch")) {
            $rules["image"] = "mimes:jpeg,png,gif|max:5000";
        }

        return $rules;
    }
}
