<?php

namespace Modules\Store\Requests\Api;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Modules\Coupon\Enums\CouponDiscountStatusEnum;
use Modules\Coupon\Enums\CouponStatusEnum;
use Modules\Store\Enums\StoreDayEnum;
use Modules\Store\Enums\StoreStatusAccountEnum;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Services\AccountService;
use Modules\Order\Enums\OrderStatusEnum;

class ComplaintRequest extends FormRequest
{
    private AccountService $accountService ;
    public function __construct(  AccountService $accountService)
    {
        $this->accountService = $accountService;
    }
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $account = $this->accountService->getAccount();
        
        $rules =
        [
            'order_id'=>
            [
                'required',
                Rule::exists('orders','id')->where('status',OrderStatusEnum::RECEIVED->value)->where('user_status',$account['status'])->where('user_id',$account['user']->id)
            ],
            'description'=>
            [
                'required',
                'string',
                'max:500'
            ],
            'reason_id'=>
            [
                'required',
                'exists:options,id'
            ]
        ];

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $attributes =
        [
            'order_id' => __('orders.id'),
            'description' => __('orders.description'),
            'reason_id' => __('orders.reason'),
        ];
        return $attributes;
    }

    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
     protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        
            $errors = (new ValidationException($validator))->errors();
            $message = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));
       
    }

}
