<?php

namespace slack\config;

use Exception;
use traits\module_config_variable;

class slack_internal_department_ids_c
{
    use module_config_variable {
        setVariableValue as private traitSetVariableValue;
    }

    /**
     * @throws Exception
     */
    public function __construct()
    {
        self::setupConfigVariable(
            'Slack',
            'internal_department_ids',
            'string',
            false,
            null,
            'JSON encoded department IDs considered internal departments for Slack goal progress notifications',
            '[1,2,3]',
            false,
            '[]'
        );
    }

    public function getDepartmentIds(): array
    {
        return self::normalizeDepartmentIds($this->getVariableValue());
    }

    /**
     * @throws Exception
     */
    public function setVariableValue(mixed $value): void
    {
        $this->traitSetVariableValue(json_encode(
            self::normalizeDepartmentIds($value),
            JSON_THROW_ON_ERROR
        ));
    }

    public static function normalizeDepartmentIds(mixed $value): array
    {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            if (is_array($decoded)) {
                $value = $decoded;
            } else {
                $value = array_filter(array_map('trim', explode(',', $value)));
            }
        }

        if (!is_array($value)) {
            return [];
        }

        $departmentIds = [];
        foreach ($value as $departmentId) {
            $departmentId = (int)$departmentId;
            if ($departmentId > 0) {
                $departmentIds[] = $departmentId;
            }
        }

        $departmentIds = array_values(array_unique($departmentIds));
        sort($departmentIds);

        return $departmentIds;
    }
}
