<?php

namespace App\Http\Requests;

use App\Enums\TaskPriority;
use App\Enums\TaskAccess;
use App\Models\Task;
use App\Models\User;
use App\Support\IdFormatter;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class TaskStoreRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Task::class);
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:10000'],
            'assigned_to' => ['nullable', 'string'],
            'priority' => ['nullable', 'string', Rule::in(TaskPriority::values())],
            'access' => ['nullable', 'string', Rule::in(TaskAccess::values())],
            'due_at' => ['nullable', 'date'],
        ];
    }

    protected function prepareForValidation()
    {
        if ($this->has('due_at') && $this->input('due_at') === '') {
            $this->merge(['due_at' => null]);
        }
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $user = $this->user();
            if (!$user->hasRole('owner') && $this->filled('assigned_to')) {
                $bin = IdFormatter::hexToBinary($this->input('assigned_to'));
                if ($bin) {
                    $target = User::find($bin);
                    if ($target && $target->hasRole('owner')) {
                        $validator->errors()->add('assigned_to', 'Không thể giao việc cho chủ sở hữu.');
                    }
                }
            }
        });
    }

    public function attributes(): array
    {
        return [
            'title' => 'Tiêu đề',
            'description' => 'Mô tả',
            'assigned_to' => 'Người được giao',
            'priority' => 'Mức ưu tiên',
            'access' => 'Đối tượng xem',
            'due_at' => 'Hạn hoàn thành',
        ];
    }
}
