<?php

namespace Ignite\Core\Http\Requests;

use Ignite\Core\Contracts\Repositories\BlockRepository;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateBlockRequest extends FormRequest
{
    public const SEGMENT_ID = 5;

    /**
     * Get the validation rules that apply to the request.
     *
     * @param  BlockRepository $blockRepository
     * @return array
     */
    public function rules(BlockRepository $blockRepository)
    {
        $block = $blockRepository->find($this->segment(static::SEGMENT_ID));

        $rules = [
            'name' => 'required|max:255',
            'code' => [
                'required', 'regex:/([a-z0-9\-\/])/',
                Rule::unique('core_block')->ignore($block->getAttribute('code'), 'code')
            ],
            'locale' => 'size:5|regex:/([a-z]){2}_([A-Z]){2}/',
            'content' => 'required',
            'status' => 'required|in:active,inactive',
            'published_at' => 'required|date_format:Y-m-d H:i:s',
        ];

        return $rules;
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'code.unique' => sprintf('The URL code `%s` has already been used.', $this->code),
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->user()->can('core.cms.blocks.update');
    }
}
