<?php

namespace App\Http\Requests\WorkOrder;

use App\Models\Production\WorkOrder;
use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        // 수주 연동 등록 시 담당자 필수
        $assigneeRequired = $this->filled('sales_order_id') ? 'required' : 'nullable';

        return [
            // 기본 정보
            'sales_order_id' => 'nullable|integer|exists:orders,id',
            'project_name' => 'nullable|string|max:200',
            'process_id' => 'required|integer|exists:processes,id',
            'status' => ['nullable', 'in:'.implode(',', WorkOrder::STATUSES)],
            'assignee_id' => 'nullable|integer|exists:users,id',
            'assignee_ids' => [$assigneeRequired, 'array'],
            'assignee_ids.*' => 'integer|exists:users,id',
            'team_id' => 'nullable|integer|exists:departments,id',
            'scheduled_date' => 'nullable|date',
            'memo' => 'nullable|string',
            'is_active' => 'nullable|boolean',

            // 품목 배열
            'items' => 'nullable|array',
            'items.*.item_id' => 'nullable|integer|exists:items,id',
            'items.*.item_name' => 'required|string|max:200',
            'items.*.specification' => 'nullable|string|max:500',
            'items.*.quantity' => 'nullable|numeric|min:0',
            'items.*.unit' => 'nullable|string|max:20',

            // 벤딩 상세 (절곡 공정인 경우)
            'bending_detail' => 'nullable|array',
            'bending_detail.shaft_cutting' => 'nullable|boolean',
            'bending_detail.bearing' => 'nullable|boolean',
            'bending_detail.shaft_welding' => 'nullable|boolean',
            'bending_detail.assembly' => 'nullable|boolean',
            'bending_detail.winder_welding' => 'nullable|boolean',
            'bending_detail.frame_assembly' => 'nullable|boolean',
            'bending_detail.bundle_assembly' => 'nullable|boolean',
            'bending_detail.motor_assembly' => 'nullable|boolean',
            'bending_detail.bracket_assembly' => 'nullable|boolean',
        ];
    }

    public function messages(): array
    {
        return [
            'process_id.required' => __('validation.required', ['attribute' => '공정']),
            'process_id.exists' => __('validation.exists', ['attribute' => '공정']),
            'assignee_ids.required' => __('error.work_order.assignee_required_for_linked'),
            'items.*.item_name.required' => __('validation.required', ['attribute' => '품목명']),
        ];
    }
}
