<?php

namespace App\Http\Requests\Content;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;

class StoreContentCategoryRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:50',
            'parent_id' => [
                'required',
                'integer',
                function ($attribute, $value, $fail) {
                    if ($value > 0) {
                        $parent = DB::table('content_categories')->where('id', $value)->first();
                        if (! $parent) {
                            $fail('父级分类不存在');

                            return;
                        }
                        if ($parent->model_id) {
                            $fail('已绑定模型的分类不允许添加子分类');
                        }
                    }
                },
            ],
            'model_id' => 'nullable|integer|exists:content_models,id',
            'icon' => 'nullable|string|max:50',
            'image' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:500',
            'sort' => 'integer|min:0',
            'status' => 'integer|in:0,1',
        ];
    }

    public function attributes(): array
    {
        return [
            'name' => '分类名称',
            'parent_id' => '父级分类',
            'model_id' => '关联模型',
            'icon' => '图标',
            'image' => '图片',
            'description' => '描述',
            'sort' => '排序',
            'status' => '状态',
        ];
    }

    public function messages(): array
    {
        return [
            'name.required' => '请输入分类名称',
            'name.max' => '分类名称不能超过50个字符',
            'parent_id.required' => '请选择父级分类',
            'parent_id.integer' => '父级分类格式错误',
            'model_id.exists' => '关联模型不存在',
            'icon.max' => '图标不能超过50个字符',
            'image.max' => '图片路径不能超过255个字符',
            'description.max' => '描述不能超过500个字符',
            'sort.min' => '排序值不能小于0',
            'status.in' => '状态值无效',
        ];
    }
}
