<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreMaterialExpenseRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'material_type_id' => ['required', 'integer', 'exists:material_types,id'],
            'expense_date' => ['required', 'date'],
            'quantity' => ['required', 'numeric', 'min:0.001'],
            'bundle_count' => ['nullable', 'integer', 'min:1', 'max:9999'],
            'unit_cost' => ['required', 'numeric', 'min:0'],
            'fattening_lot_id' => ['nullable', 'integer', 'exists:fattening_lots,id'],
            'adds_to_inventory' => ['sometimes', 'boolean'],
            'notes' => ['nullable', 'string', 'max:500'],
        ];
    }

    protected function prepareForValidation(): void
    {
        $qty = (float) $this->input('quantity', 0);
        $unit = (float) $this->input('unit_cost', 0);
        $this->merge([
            'total_cost' => round($qty * $unit, 2),
        ]);
    }
}
