<?php

namespace App\Http\Requests\Admin;

use Illuminate\Validation\Rule;
use App\Enums\ProductStatusEnum;
use Illuminate\Foundation\Http\FormRequest;

class ProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        if (!$this->has('user_id') || empty($this->input('user_id'))) {
            $this->merge([
                'user_id' => auth()->id(),
            ]);
        }

        $this->merge([
            'second_hand' => $this->has('second_hand') ? true : false,
            'consumable' => $this->has('consumable') ? true : false,
        ]);
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $isUpdate = $this->isMethod('put') || $this->isMethod('patch');

        return [
            'user_id' => ['required', 'exists:users,id'],
            'category_id' => ['required', 'exists:categories,id'],
            'brand_id' => ['nullable', 'exists:brands,id'],

            'title' => ['required', 'string', 'max:255'],
            'code' => ['nullable', 'string', 'max:255'],

            'slug' => ['required', 'string', 'max:500'],

            'short_description' => ['nullable', 'string', 'max:255'],
            'content' => ['nullable', 'string'],

            'inventory' => ['nullable', 'numeric'],
            'weight' => ['nullable', 'numeric'],
            'length' => ['nullable', 'numeric'],
            'width' => ['nullable', 'numeric'],
            'height' => ['nullable', 'numeric'],
            'price' => ['nullable', 'numeric'],

            'discount_price' => ['nullable', 'numeric'],
            'off_rate' => ['nullable', 'numeric'],

            'second_hand' => ['nullable', 'boolean'],
            'consumable' => ['nullable', 'boolean'],

            'status' => ['required', Rule::in(ProductStatusEnum::values())],

            'image' => $isUpdate
                ? ['nullable', 'image', 'max:2048']
                : ['required', 'image', 'max:2048'],

            'images' => ['nullable', 'array'],
            'images.*' => ['nullable', 'image', 'max:2048'],

            'delete_images' => ['nullable'],
            'tag' => ['nullable'],

            'attributes' => ['nullable', 'array'],
        ];
    }
}
