<?php

namespace App\Modules\HR\Recruitment\Requests;

use App\Modules\HR\Recruitment\Models\RecruitmentApplication;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreApplicationRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', RecruitmentApplication::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 [
            'vacancy_id' => [
                'required',
                'integer',
                Rule::exists('recruitment_vacancies', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId)->whereNull('deleted_at')
                ),
            ],
            'candidate_id' => [
                'required',
                'integer',
                Rule::exists('recruitment_candidates', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId)->whereNull('deleted_at')
                ),
            ],
            'candidate_cv_id' => [
                'nullable',
                'integer',
                Rule::exists('recruitment_candidate_cvs', 'id')->where(function ($q) use ($tenantId) {
                    $q->where('tenant_id', $tenantId)
                        ->where('candidate_id', (int) $this->input('candidate_id'))
                        ->whereNull('deleted_at');
                }),
            ],
            'source' => ['nullable', 'string', 'max:80'],
            'cover_letter' => ['nullable', 'string', 'max:10000'],
        ];
    }
}
