<?php

namespace App\Http\Requests\Sales;

use App\Enums\PaymentMethod;
use App\Http\Messages\ErrorMessages;
use App\Http\Responses\ApiResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rules\Enum;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'social_reason' => 'sometimes|string|max:255',
            'nit' => 'sometimes|string|max:255',
            'opportunity_id' => 'required',
            'payment_method' => ['sometimes', new Enum(PaymentMethod::class)],
            'delivery_date'=> 'sometimes|date',
            'amount' => 'required',
            'initial_fee' => 'required',
            'percentage_initial_fee' => 'nullable',
            'is_payment_initial_fee' => 'nullable|boolean',
            'quote_id' => 'nullable',
            'stage_id' => 'nullable',
            'creation_date' => 'nullable',


            'properties' => 'required|array',
            'properties.*.property_id' => 'required',
            'properties.*.price' => 'required',

            'differs_initial_fee' => 'nullable|array',
            'differs_initial_fee.*.date' => 'nullable',
            'differs_initial_fee.*.amount' => 'nullable|numeric',
            'differs_initial_fee.*.is_paid' => 'nullable|boolean',

            'differs_balance' => 'nullable|array',
            'differs_balance.*.date' => 'nullable',
            'differs_balance.*.amount' => 'nullable|numeric',
            'differs_initial_fee.*.is_paid' => 'nullable|boolean',
        ];
    }
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            ApiResponse::error(
                ErrorMessages::UNPROCESSABLE_ENTITY,
                $validator->errors(),
                [],
                422
            )
        );
    }
}
