<?php

namespace App\Http\Requests\ProjectManagement;

use App\Models\Admin\AdminPmIssue;
use App\Models\Admin\AdminPmTask;
use Illuminate\Foundation\Http\FormRequest;

class BulkActionRequest 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.
     */
    public function rules(): array
    {
        $rules = [
            'ids' => 'required|array|min:1',
            'ids.*' => 'required|integer',
            'action' => 'required|in:change_status,change_priority,change_assignee,change_type,link_task,delete,restore',
        ];

        // 액션에 따른 추가 유효성 검사
        switch ($this->input('action')) {
            case 'change_status':
                $statusOptions = $this->getStatusOptions();
                $rules['value'] = 'required|in:'.implode(',', $statusOptions);
                break;
            case 'change_priority':
                $rules['value'] = 'required|in:'.implode(',', array_keys(AdminPmTask::getPriorities()));
                break;
            case 'change_assignee':
                $rules['value'] = 'nullable|exists:users,id';
                break;
            case 'change_type':
                $rules['value'] = 'required|in:'.implode(',', array_keys(AdminPmIssue::getTypes()));
                break;
            case 'link_task':
                $rules['value'] = 'nullable|exists:admin_pm_tasks,id';
                break;
        }

        return $rules;
    }

    /**
     * Get status options based on resource type.
     */
    protected function getStatusOptions(): array
    {
        $type = $this->input('type', 'task');

        if ($type === 'issue') {
            return array_keys(AdminPmIssue::getStatuses());
        }

        return array_keys(AdminPmTask::getStatuses());
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'ids' => '선택된 항목',
            'ids.*' => '항목 ID',
            'action' => '작업',
            'value' => '값',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     */
    public function messages(): array
    {
        return [
            'ids.required' => '최소 하나의 항목을 선택해주세요.',
            'ids.array' => '선택된 항목이 올바르지 않습니다.',
            'ids.min' => '최소 하나의 항목을 선택해주세요.',
            'ids.*.integer' => '항목 ID가 올바르지 않습니다.',
            'action.required' => '수행할 작업을 선택해주세요.',
            'action.in' => '올바른 작업을 선택해주세요.',
            'value.required' => '값을 입력해주세요.',
            'value.in' => '올바른 값을 선택해주세요.',
            'value.exists' => '존재하지 않는 항목입니다.',
        ];
    }
}
