<?php

namespace App\Http\Requests\Admin\Quiz;

use App\Enums\DifficultyLevelEnums;
use App\Enums\QuizStatusEnum;
use Illuminate\Foundation\Http\FormRequest;

class QuizRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth('admin')->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'lang' => 'required|array',
            'lang.*.locale' => 'required|string|',
            'lang.*.title' => 'required|string|max:191',
            'lang.*.tags' => 'nullable|array',
            'lang.*.tags.*' => 'nullable|string',
            'lang.*.description' => 'required|string|max:2000',
            'category_id' => 'required|exists:quiz_categories,id',
            'quiz_level' => 'required|in:'.implode(',', DifficultyLevelEnums::values()),
            'has_level' => 'required|in:1,0',
            'image' => 'nullable|string',
            'banner_image' => 'nullable|string',
            'tags.*' => 'nullable|string',
            'is_free' => 'required|boolean',
            'point_to_pass' => 'required_if:is_free,false|integer|min:0',
            'status' => 'nullable|in:'.implode(',', QuizStatusEnum::values()),
        ];
    }

    public function prepareForValidation()
    {
        if ($this->is_free) {
            $this->merge([
                'point_to_pass' => 0,
            ]);
        }

    }

    public function quizValidated(): array
    {
        $validated = $this->validated();

        return [
            'image' => $validated['image'],
            'banner_image' => $validated['banner_image'],
            'category_id' => $validated['category_id'],
            'quiz_level' => $validated['quiz_level'],
            'has_level' => $validated['has_level'],
            'point_to_pass' => $validated['point_to_pass'],
            'is_free' => $validated['is_free'],
        ];
    }

    public function messages(): array
    {
        return [
            'lang.*.title.required' => __('The title field is required'),
            'lang.*.description.required' => __('The description field is required'),
            'lang.*.locale.required' => __('The locale field is required'),
        ];
    }
}
