<?php

namespace App\Http\Requests\Recruitment;

class UpdateJobDemandRequest extends StoreJobDemandRequest
{
    public function rules(): array
    {
        $rules = parent::rules();

        // The employer of an existing demand never changes; raise a new one instead.
        unset($rules['employer_id']);
        $rules['job_title'] = ['sometimes', 'string', 'max:255'];
        $rules['quantity_required'] = ['sometimes', 'integer', 'min:1', 'max:100000'];
        // On a partial update the currency may already be stored, so it is not
        // unconditionally required alongside the amount (see withValidator).
        $rules['salary_currency'] = ['nullable', 'string', 'size:3'];

        return $rules;
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $demand = $this->route('jobDemand');

            if ($this->filled('salary_amount')
                && blank($this->input('salary_currency'))
                && blank($demand?->salary_currency)) {
                $validator->errors()->add('salary_currency', 'A salary currency is required with a salary amount.');
            }
        });
    }

    /** @return array<string, mixed> */
    public function modelAttributes(): array
    {
        return array_intersect_key(parent::modelAttributes(), $this->all());
    }
}
