<?php

namespace Modules\HR\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Modules\HR\Models\SalaryComponent;

class UniqueBasicSalaryComponent implements ValidationRule
{
    protected ?int $ignoreId;

    public function __construct($ignoreId = null)
    {
        $this->ignoreId = $ignoreId;
    }

    /**
     * Validate only one "is_basic = true" exists
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!$value) {
            return;
        }

        $query = SalaryComponent::where('is_basic', true);

        if ($this->ignoreId) {
            $query->where('id', '!=', $this->ignoreId);
        }

        if ($query->exists()) {
            $fail('Only one salary component can be marked as basic.');
        }
    }
}
