<?php

namespace App\Modules\HR\Recruitment\Requests;

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

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

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

        return [
            'candidate_id' => [
                'required',
                'integer',
                Rule::exists('recruitment_candidates', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tenantId)->whereNull('deleted_at')
                ),
            ],
            'file' => ['required', 'file', 'max:10240', 'mimes:pdf,doc,docx'],
            'is_primary' => ['sometimes', 'boolean'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->route('candidate') !== null && ! $this->filled('candidate_id')) {
            $this->merge(['candidate_id' => $this->route('candidate')->id ?? $this->route('candidate')]);
        }
        if ($this->has('is_primary')) {
            $this->merge(['is_primary' => $this->boolean('is_primary')]);
        }
    }
}
