<?php

namespace App\Http\Requests\MiscIssue;

use App\Models\InventoryMovement;
use Illuminate\Foundation\Http\FormRequest;

class MiscIssueRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'transaction_date' => 'required',
            'transaction_type' => 'required|string',
            'remarks' => 'nullable|string',
            'items' => 'required|array|min:1',

            'items.*.item_id' => 'required|exists:items,id',
            'items.*.quantity' => 'required|numeric|min:0.001',
            'items.*.unit_cost' => 'nullable|numeric|min:0',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {

            $farmId = auth()->user()->farm_id;

            foreach ($this->items ?? [] as $index => $row) {

                $line = $index + 1;

                if (!empty($row['item_id']) && !empty($row['quantity'])) {

                    $stock = InventoryMovement::where('item_id', $row['item_id'])
                        ->where('farm_id', $farmId)
                        ->selectRaw("
                        COALESCE(SUM(CASE WHEN type = 'IN' THEN quantity ELSE 0 END),0)
                        - 
                        COALESCE(SUM(CASE WHEN type = 'OUT' THEN quantity ELSE 0 END),0)
                        as balance
                    ")
                        ->value('balance') ?? 0;

                    if ($stock < $row['quantity']) {
                        $validator->errors()->add(
                            "items.$index.quantity",
                            "Line {$line}: Insufficient stock. Available: {$stock}"
                        );
                    }
                }
            }
        });
    }
}
