<?php

namespace App\Modules\Sales\Requests;

use App\Modules\Inventory\Stock\Support\DecimalQuantity;
use App\Modules\Sales\Models\SalesOrder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class FulfillSalesOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'confirmation' => ['required', 'string', 'in:FULFILL_ORDER'],
            'operation_batch' => ['required', 'uuid'],
            'lines' => ['required', 'array', 'min:1'],
            'lines.*.line_id' => ['required', 'integer', 'min:1'],
            'lines.*.quantity' => ['nullable', 'string', 'max:32'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $v): void {
            /** @var SalesOrder|null $order */
            $order = $this->route('sales_order');
            if ($order === null) {
                return;
            }
            $allowed = $order->lines()->pluck('id')->map(fn ($id) => (int) $id)->all();
            foreach ($this->input('lines', []) as $i => $row) {
                $lid = (int) ($row['line_id'] ?? 0);
                if (! in_array($lid, $allowed, true)) {
                    $v->errors()->add('lines.'.$i.'.line_id', __('sales.validation.line_not_on_order'));
                }
            }
            $any = false;
            foreach ($this->input('lines', []) as $row) {
                $qty = trim((string) ($row['quantity'] ?? ''));
                if ($qty !== '' && DecimalQuantity::gtZero($qty)) {
                    $any = true;
                    break;
                }
            }
            if (! $any) {
                $v->errors()->add('lines', __('sales.validation.fulfill_qty_required'));
            }
        });
    }
}
