<?php

namespace App\Modules\HR\Performance\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class PerformanceRequest extends FormRequest
{
    public function authorize(): bool
    {
        if ($this->routeIs('me.*')) {
            return true;
        }
        if ($this->routeIs('*.manager')) {
            return $this->user()?->can('performance.manage') ?? false;
        }
        if ($this->isMethod('PUT')) {
            return $this->user()?->can('performance.update') ?? false;
        }

        return $this->user()?->can('performance.create') ?? false;
    }

    public function rules(): array
    {
        $review = [
            'self_score' => ['nullable', 'numeric', 'between:0,100'], 'manager_score' => ['nullable', 'numeric', 'between:0,100'],
            'final_score' => ['nullable', 'numeric', 'between:0,100'], 'goals' => ['nullable', 'array'], 'kpis' => ['nullable', 'array'],
            'self_assessment' => ['nullable', 'string'], 'manager_review' => ['nullable', 'string'],
            'promotion_recommended' => ['sometimes', 'boolean'], 'training_recommended' => ['sometimes', 'boolean'],
        ];
        if ($this->routeIs('*.reviews.store')) {
            return $review + [
                'employee_id' => ['required', 'integer', 'exists:employees,id'],
                'cycle_id' => ['required', 'integer', 'exists:hr_performance_cycles,id'],
            ];
        }
        if ($this->route('review')) {
            return $review;
        }

        return [
            'name' => ['required', 'string', 'max:255'], 'starts_at' => ['required', 'date'],
            'ends_at' => ['required', 'date', 'after_or_equal:starts_at'], 'status' => ['required', Rule::in(['draft', 'active', 'closed'])],
        ];
    }
}
