<?php

namespace App\Modules\HR\Training\Requests;

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

class TrainingRequest extends FormRequest
{
    public function authorize(): bool
    {
        if ($this->routeIs('*.enroll')) {
            return $this->user()?->can('training.manage') ?? false;
        }

        return $this->user()?->can($this->isMethod('PUT') ? 'training.update' : 'training.create') ?? false;
    }

    public function rules(): array
    {
        $tenant = $this->user()?->tenant_id;
        if ($this->routeIs('*.enroll')) {
            return ['employee_ids' => ['required', 'array'], 'employee_ids.*' => [Rule::exists('employees', 'id')->where(fn ($q) => $q->where('tenant_id', $tenant))]];
        }
        if ($this->routeIs('*.sessions.store') || $this->route('session')) {
            return [
                'trainer' => ['nullable', 'string'], 'location' => ['nullable', 'string'],
                'starts_at' => ['required', 'date'], 'ends_at' => ['required', 'date', 'after:starts_at'],
                'capacity' => ['nullable', 'integer', 'min:1'], 'status' => ['required', Rule::in(['planned', 'open', 'completed', 'cancelled'])],
            ];
        }

        return [
            'code' => ['required', 'string', 'max:50'], 'name' => ['required', 'string'],
            'description' => ['nullable', 'string'], 'default_hours' => ['nullable', 'numeric', 'min:0'],
            'default_cost' => ['nullable', 'numeric', 'min:0'], 'is_active' => ['sometimes', 'boolean'],
        ];
    }
}
