<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class DealershipDepartmentHasPrimaryRule implements Rule
{
    public function passes($attribute, $departments)
    {
        if (empty($departments)) {
            return true;
        }

        // the rule passes if we have exactly one department where is_primary is true
        return collect($departments)
                ->pluck('is_primary')
                ->filter(fn ($item) => $item)
                ->count() === 1;
    }

    public function message()
    {
        return 'A dealership must have exactly one primary department';
    }
}
