<?php

namespace App\Http\Requests\Manufacturing;

use App\Http\Requests\BaseFormRequest;
use App\Models\SkuMovement;

class StoreSkuMovementRequest extends BaseFormRequest
{
    public function rules(): array
    {
        return [
            'sku_id' => 'required|exists:skumaster,id',
            'type' => 'required|in:' . implode(',', SkuMovement::getTypes()),
            'quantity' => 'required|numeric|min:0.01',
            'reference' => 'nullable|string|max:100',
            'product' => 'nullable|string|max:255',
            'from_location' => 'nullable|string|max:100',
            'to_location' => 'nullable|string|max:100',
            'date' => 'required|date',
            'status' => 'nullable|in:' . implode(',', SkuMovement::getStatuses()),
            'notes' => 'nullable|string|max:1000',
        ];
    }

    public function attributes(): array
    {
        return [
            'sku_id' => 'SKU',
            'type' => 'Movement Type',
            'quantity' => 'Quantity',
            'from_location' => 'From Location',
            'to_location' => 'To Location',
        ];
    }

    public function messages(): array
    {
        return [
            'sku_id.required' => 'SKU is required.',
            'sku_id.exists' => 'Selected SKU does not exist.',
            'type.required' => 'Movement type is required.',
            'type.in' => 'Invalid movement type. Must be inbound, outbound, transfer, or adjustment.',
            'quantity.required' => 'Quantity is required.',
            'quantity.min' => 'Quantity must be greater than zero.',
            'date.required' => 'Movement date is required.',
        ];
    }

    /**
     * Configure validation for transfer movements
     */
    public function withValidator($validator)
    {
        $validator->sometimes('from_location', 'required', function ($input) {
            return in_array($input->type, [SkuMovement::TYPE_OUTBOUND, SkuMovement::TYPE_TRANSFER]);
        });

        $validator->sometimes('to_location', 'required', function ($input) {
            return in_array($input->type, [SkuMovement::TYPE_INBOUND, SkuMovement::TYPE_TRANSFER]);
        });
    }
}
