<?php

namespace App\Http\Requests\General;

use App\Models\Post;
use App\Enums\PostType;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class PostSaveRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        if ($this->input('id')) {
            return Post::owned()->find($this->input('id'))?->exists();
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $originIdRules = match ($this->input('type')) {
            PostType::GROUP->value => ['required', 'exists:groups,id,deleted_at,NULL'],
            PostType::SHARE_PUBLIC->value, PostType::SHARE_FRIENDS->value, PostType::SHARE_PRIVATE->value => ['required', 'exists:posts,id,deleted_at,NULL'],
            default => ['nullable'],
        };

        return [
            'id' => ['nullable', 'exists:posts,id,deleted_at,NULL'],
            'content' => ['required', 'string', 'max:2000'],
            'type' => ['required', Rule::in(PostType::values())],
            'origin_id' => $originIdRules,
            'images' => ['nullable', 'array'],
            'images.*' => ['image', 'max:10000'],
        ];
    }
}
