<?php

namespace App\Http\Requests\Approval;

use App\Models\Tenants\ApprovalLine;
use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        $stepTypes = implode(',', ApprovalLine::STEP_TYPES);

        return [
            // form_id 또는 form_code 중 하나 필수
            'form_id' => 'required_without:form_code|integer|exists:approval_forms,id',
            'form_code' => 'required_without:form_id|string|exists:approval_forms,code',
            'title' => 'required|string|max:200',
            'content' => 'required|array',
            'attachments' => 'nullable|array',
            'attachments.*' => 'integer|exists:files,id',
            'submit' => 'nullable|boolean',
            'steps' => 'required_if:submit,true|array|min:1',
            // type 또는 step_type
            'steps.*.type' => "nullable|string|in:{$stepTypes}",
            'steps.*.step_type' => "nullable|string|in:{$stepTypes}",
            // user_id 또는 approver_id
            'steps.*.user_id' => 'nullable|integer|exists:users,id',
            'steps.*.approver_id' => 'nullable|integer|exists:users,id',
            'steps.*.step_order' => 'nullable|integer|min:1',
        ];
    }

    public function messages(): array
    {
        return [
            'form_id.required' => __('validation.required', ['attribute' => '결재양식']),
            'form_id.exists' => __('validation.exists', ['attribute' => '결재양식']),
            'title.required' => __('validation.required', ['attribute' => '제목']),
            'content.required' => __('validation.required', ['attribute' => '내용']),
            'steps.required_if' => __('error.approval.steps_required'),
            'steps.min' => __('validation.min.array', ['attribute' => '결재단계', 'min' => 1]),
        ];
    }
}
