<?php

namespace App\Modules\HR\Recruitment\Requests;

use App\Modules\HR\Recruitment\Models\RecruitmentVacancy;
use App\Modules\HR\Recruitment\Support\JobRequestStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreVacancyRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', RecruitmentVacancy::class) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return $this->baseRules();
    }

    /**
     * @return array<string, mixed>
     */
    protected function baseRules(): array
    {
        $tenantId = $this->user()?->tenant_id;

        return [
            'job_request_id' => [
                'required',
                'integer',
                Rule::exists('recruitment_job_requests', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId)
                        ->where('status', JobRequestStatus::APPROVED)
                        ->whereNull('deleted_at')
                ),
            ],
            'department_id' => [
                'required',
                'integer',
                Rule::exists('departments', 'id')->where(fn ($q) => $q->where('tenant_id', $tenantId)),
            ],
            'position_id' => [
                'nullable',
                'integer',
                Rule::exists('positions', 'id')->where(function ($q) use ($tenantId) {
                    $q->where('tenant_id', $tenantId)
                        ->where('department_id', (int) $this->input('department_id'));
                }),
            ],
            'title' => ['required', 'string', 'max:200'],
            'description' => ['nullable', 'string', 'max:10000'],
            'openings' => ['required', 'integer', 'min:1', 'max:999'],
            'closes_at' => ['nullable', 'date'],
        ];
    }
}
