<?php

namespace App\Rules;

use App\IntegrationRepository;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Log;

class ExceedsMaxEnabledCountRule implements Rule
{
    protected $max_count = 0;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(protected readonly ?array $allInput = [])
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // We need to make sure all flags are ok
        return collect($value)
            ->reject(fn($entryValue, $entryAttribute) => $this->checkEachValue($entryAttribute, $entryValue))
            ->isEmpty();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Maximum of enabled integrations exceeded. Allowed count: ' . $this->max_count;
    }

    private function checkEachValue($attribute, $value): bool
    {
        $attributeToCheck = str_replace('values.', '', $attribute);
        $repository = new IntegrationRepository();
        if ($repository->keyIsEnableSettingValue($attributeToCheck) === false) {
            return true;
        }

        if ($value !== true) {
            return true;
        }

        $type = $repository->getTypeFromKey($attributeToCheck);
        $this->max_count = $repository->getLimitForType($type, tenant()->tier);

        return $repository->checkEnabledCountForType($this->allInput, $type) <= $this->max_count;
    }
}
