<?php

namespace App\Http\Requests;

use App\Models\InventoryTransferDocument;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreInventoryTransferDocumentRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', InventoryTransferDocument::class);
    }

    public function rules(): array
    {
        return array_merge($this->headerRules(), [
            'folio' => ['required', 'string', 'max:64', 'unique:inventory_transfer_documents,folio'],
            'lines' => ['required', 'array', 'min:1'],
        ]);
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    protected function headerRules(): array
    {
        return [
            'transfer_type' => ['required', 'string', Rule::in([
                InventoryTransferDocument::TRANSFER_INBOUND_RECEIPT,
                InventoryTransferDocument::TRANSFER_INTERNAL_DELIVERY,
                InventoryTransferDocument::TRANSFER_OUTBOUND,
            ])],
            'destination_area_id' => ['nullable', 'integer', 'exists:areas,id'],
            'recipient_user_id' => ['nullable', 'integer', 'exists:users,id'],
            'supplier_id' => ['nullable', 'integer', 'exists:inventory_suppliers,id'],
            'supplier_reference' => ['nullable', 'string', 'max:128'],
            'notes' => ['nullable', 'string'],
            'lines.*.inventory_product_id' => [
                'required',
                'integer',
                Rule::exists('inventory_products', 'id')->where('active', true),
            ],
            'lines.*.quantity' => ['required', 'numeric', 'min:0.0001'],
            'lines.*.sort_order' => ['sometimes', 'integer', 'min:0'],
        ];
    }
}
