<?php

namespace App\Http\Requests\StockManagement;

use App\Exceptions\DatatableEditorValidationException;
use App\Models\ProductManagement\Product;
use App\Models\StockManagement\Stock;
use App\Models\StockManagement\Warehouse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CreateAdjustmentRequest extends FormRequest{

    public function authorize(){
        $data = (array) request()->get("data")[0];
        unset($data['info']);
        $this->replace([
            "lot_id" => $data['lot_id'],
            "qty" => $data['qty'],
            "expired_at" => $data['expired_at'],
            "product_id" => $data['product_id'],
            "warehouse_id" => $data['warehouse_id'],
        ]);
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     * @return array<string, mixed>
     */
    public function rules(){
        $product_table = (new Product)->getTable();
        $warehouse_table = (new Warehouse)->getTable();
        $stock_table = (new Stock)->getTable();
        $data = $this->all();

        $rules = [
            "lot_id" => ['required', "min:2",'max:60',
                Rule::unique($stock_table,"lot_id")
                    ->where(function ($query) use($data){
                        //return $query->where('product_id',$data['product_id'])
                        return $query->where('warehouse_id',$data['warehouse_id']);
                    })
            ],
            "qty" => ['required', 'numeric', "min:1"],
            "expired_at" => ['required', 'date','date_format:d-m-Y'],
            "product_id" => ['required',"exists:$product_table,id"],
            "warehouse_id" => ['required',"exists:$warehouse_table,id,deleted_at,NULL"],
        ];

        if ($this->routeIs("api.resources.create")){
            // $rules['service_id'] = ["required",'int',"exists:$services_table,id"];
            $rules['password'] = ['required', 'confirmed', "min:4"];
        }
        elseif ($this->routeIs("api.resources.delete")){
            $rules = [];
        }
        elseif ($this->routeIs("api.resources.delete-many")){
            $rules = [
                "ids" => ['required',"array","min:1"],
                "ids.*" => ['required',"int","exists:$stock_table,id,deleted_at,NULL"],
            ];
        }
        elseif ($this->routeIs("api.resources.activate")){
            $rules = ["is_active" => ["required","boolean"] ];
        }

        return $rules;
    }

    public function attributes(){
        return  [
            'lot_id' => __("Id Lot"),
            'qty' => __("Quantité"),
            'expired_at' => __("Date d'Expiration"),
            'product_id' => __("Id Produit"),
            'warehouse_id' => __("Entrepôt"),
            "ids" => __("Stock"),
            "ids.*" => __("Stocks"),
        ];
    }

    public function messages(){
        $data =  $this->all();
        if (!empty($data['product_id']) and !empty($data['lot_id']) ){
            $product = Product::find($data['product_id']);
            return [
                "lot_id.unique" => __("Le Lot ':lot_id' existe déja sur le produit : ':product'.
                 Il est recommandé de faire plutot un ajustement sur ce lot",
                    ['lot_id' => $data['lot_id'], "product" => $product->fullName ?? ""])
            ];
        }
        return [];
    }

    /** Se produit lorsque la validation a echoué
     * @param Validator $validator
     * @throws DatatableEditorValidationException
     */
    protected function failedValidation(Validator $validator){
        throw new DatatableEditorValidationException($validator);
    }



}
