<?php

namespace App\Http\Requests\Stock;

use App\Models\StockTransferOut;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class StockTransferInRequest 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 [
            'stock_transfer_out_id' => ['required', 'integer', 'exists:stock_transfer_outs,id'],
            'received_date'         => ['required', 'date'],
            'remarks'               => ['nullable', 'string'],
            'items'                 => ['required', 'array', 'min:1'],
            'items.*.item_id'       => ['required', 'integer', 'exists:items,id'],
            'items.*.quantity'      => ['required', 'numeric', 'min:0.0001'],
        ];
    }

    public function messages(): array
    {
        return [
            'stock_transfer_out_id.required' => 'Transfer Out reference is required.',
            'stock_transfer_out_id.exists'   => 'Selected Transfer Out does not exist.',
            'received_date.required'         => 'Received date is required.',
            'items.required'                 => 'At least one item is required.',
            'items.min'                      => 'At least one item is required.',
            'items.*.item_id.required'       => 'Item is required.',
            'items.*.item_id.exists'         => 'Selected item does not exist.',
            'items.*.quantity.required'      => 'Quantity is required.',
            'items.*.quantity.min'           => 'Quantity must be greater than zero.',
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $transferOutId = $this->input('stock_transfer_out_id');

            if (!$transferOutId) {
                return;
            }

            $farmId     = Auth::user()->farm_id;
            $transferOut = StockTransferOut::find($transferOutId);

            if (!$transferOut) {
                return;
            }

            if ($transferOut->source_farm_id === $farmId) {
                $validator->errors()->add(
                    'stock_transfer_out_id',
                    'You cannot receive a transfer that your farm sent.'
                );
                return;
            }

            if ($transferOut->destination_farm_id !== $farmId) {
                $validator->errors()->add(
                    'stock_transfer_out_id',
                    'This transfer is not intended for your farm.'
                );
                return;
            }

            if (!in_array($transferOut->status, ['pending', 'partially_received'])) {
                $validator->errors()->add(
                    'stock_transfer_out_id',
                    'This transfer is already completed or cancelled.'
                );
                return;
            }

            // Validate each submitted item exists on the Transfer Out
            // and does not exceed its remaining quantity.
            $items = $this->input('items', []);

            foreach ($items as $index => $row) {
                $itemId = $row['item_id'] ?? null;
                $qty    = $row['quantity'] ?? 0;

                if (!$itemId) {
                    continue;
                }

                $transferOutItem = \App\Models\StockTransferOutItem::where('stock_transfer_out_id', $transferOut->id)
                    ->where('item_id', $itemId)
                    ->first();

                if (!$transferOutItem) {
                    $validator->errors()->add(
                        "items.{$index}.item_id",
                        'This item does not exist in the selected Transfer Out.'
                    );
                    continue;
                }

                if ($qty > $transferOutItem->remaining_qty) {
                    $validator->errors()->add(
                        "items.{$index}.quantity",
                        "Quantity exceeds remaining transfer quantity. Remaining: {$transferOutItem->remaining_qty}"
                    );
                }
            }
        });
    }
}
