<?php

namespace App\Http\Requests;

use App\Enums\DietType;
use App\Enums\IngredientUnit;
use App\Enums\MealPostType;
use App\Enums\MealPostVisibility;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class MealPostsRequest extends FormRequest
{
    public function rules(): array
    {
        $isCreating = $this->isMethod('post');

        return [
            'image' => [$isCreating ? 'required_without:image_url' : 'sometimes', 'nullable', 'image', 'max:4096'],
            'image_url' => [$isCreating ? 'required_without:image' : 'sometimes', 'nullable', 'string', 'max:2048'],
            'caption' => ['nullable', 'string', 'max:1000'],
            'calories' => ['nullable', 'integer', 'min:0'],
            'proteins' => ['nullable', 'numeric', 'min:0'],
            'carbs' => ['nullable', 'numeric', 'min:0'],
            'fats' => ['nullable', 'numeric', 'min:0'],
            'title' => [$isCreating ? 'required' : 'sometimes', 'string', 'max:255'],
            'eaten_at' => [$isCreating ? 'required' : 'sometimes', 'date'],
            'type' => [$isCreating ? 'required' : 'sometimes', Rule::enum(MealPostType::class)],
            'visibility' => ['sometimes', Rule::enum(MealPostVisibility::class)],
            'diet_type' => ['sometimes', Rule::enum(DietType::class)],
            'ingredients' => ['sometimes', 'array'],
            'ingredients.*' => ['required', 'array:position,ingredient,quantity,unit'],
            'ingredients.*.position' => ['required', 'integer', 'min:0'],
            'ingredients.*.ingredient' => ['required', 'string', 'max:255'],
            'ingredients.*.quantity' => ['required', 'integer', 'min:1'],
            'ingredients.*.unit' => ['required', Rule::enum(IngredientUnit::class)],
        ];
    }

    public function authorize(): bool
    {
        return true;
    }

    public function messages(): array
    {
        return [
            'image.max' => __('api.validation.image_max_4mb'),
            'image_url.required_without' => __('api.validation.meal_image_required'),
            'visibility' => __('api.validation.visibility_valid'),
        ];
    }
}
