<?php

namespace App\Http\Requests\Mortality;

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

class UpdateRequest 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 [
            'synced_status'                       => 'required|string',

            'mortality_line'                      => 'required|array|min:1',
            'mortality_line.*.id'                 => 'nullable|exists:mortality_line,id',
            'mortality_line.*.batch_id'           => 'required|exists:batches,id',
            'mortality_line.*.batch_no'           => 'required|string',
            'mortality_line.*.building_id'        => 'required|exists:buildings,id',
            'mortality_line.*.building_name'      => 'required|string',
            'mortality_line.*.mortality_date'     => 'required|date_format:m/d/Y',
            'mortality_line.*.quantity'           => 'required|integer|min:1',
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $id = $this->route()->mortality; // or whatever your route parameter is named

            if (!Mortality::where('id', $id)->exists()) {
                $validator->errors()->add('id', 'Mortality ID record does not exist.');
            }
        });
    }
}
