<?php

namespace App\Http\Requests\Manufacturing;

use App\Http\Requests\BaseFormRequest;

class StoreQualityControlRequest extends BaseFormRequest
{
    public function rules(): array
    {
        return [
            'route_card_id' => 'required|exists:route_cards,id',
            'process_id' => 'required|exists:route_card_processes,id',
            'inspection_date' => 'required|date',
            'inspector_id' => 'required|exists:employee_details,id',
            'stage' => 'required|in:before,during,after',
            'status' => 'required|in:pending,passed,failed,conditional',
            'quantity_inspected' => 'required|numeric|min:0',
            'quantity_passed' => 'required|numeric|min:0',
            'quantity_failed' => 'nullable|numeric|min:0',
            'remarks' => 'nullable|string|max:2000',
            'parameters' => 'nullable|array',
            'parameters.*.name' => 'required_with:parameters|string|max:100',
            'parameters.*.specification' => 'nullable|string|max:200',
            'parameters.*.actual_value' => 'required_with:parameters|string|max:100',
            'parameters.*.status' => 'required_with:parameters|in:pass,fail',
        ];
    }

    public function attributes(): array
    {
        return [
            'route_card_id' => 'Route Card',
            'process_id' => 'Process',
            'inspection_date' => 'Inspection Date',
            'inspector_id' => 'Inspector',
            'quantity_inspected' => 'Quantity Inspected',
            'quantity_passed' => 'Quantity Passed',
        ];
    }

    public function messages(): array
    {
        return [
            'quantity_passed.max' => 'Quantity passed cannot exceed quantity inspected.',
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $inspected = $this->input('quantity_inspected', 0);
            $passed = $this->input('quantity_passed', 0);

            if ($passed > $inspected) {
                $validator->errors()->add('quantity_passed', 'Quantity passed cannot exceed quantity inspected.');
            }
        });
    }
}
