<?php

namespace App\Modules\HR\Payroll\Requests;

use App\Modules\HR\Payroll\Models\SalaryStructure;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return array_merge($this->baseRules(), [
            'code' => [
                'required', 'string', 'max:64',
                Rule::unique('hr_salary_structures', 'code')
                    ->where(fn ($q) => $q->where('tenant_id', $this->user()?->tenant_id))
                    ->ignore($this->route('salary_structure')?->id),
            ],
        ]);
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'is_active' => $this->boolean('is_active', true),
            'currency' => strtoupper((string) $this->input('currency', 'USD')),
        ]);
    }

    /**
     * @return array<string, mixed>
     */
    protected function baseRules(): array
    {
        return [
            'name' => ['required', 'string', 'max:120'],
            'description' => ['nullable', 'string', 'max:2000'],
            'currency' => ['required', 'string', 'size:3', 'alpha'],
            'is_active' => ['sometimes', 'boolean'],
            'components' => ['nullable', 'array'],
            'components.*.id' => ['nullable', 'integer'],
            'components.*.code' => ['nullable', 'string', 'max:64'],
            'components.*.name' => ['required', 'string', 'max:120'],
            'components.*.component_type' => ['required', 'string', Rule::in(['earning', 'deduction', 'employer_contribution'])],
            'components.*.calculation' => ['required', 'string', Rule::in(['fixed', 'percentage'])],
            'components.*.amount' => ['required', 'numeric', 'min:0'],
            'components.*.is_taxable' => ['sometimes', 'boolean'],
            'components.*.sort_order' => ['nullable', 'integer', 'min:0'],
        ];
    }
}
