<?php

namespace classes;

use Exception;

class department_relay_config
{
    public ?string $what_happens = null;
    public ?string $webhook_token = null;

    /**
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $this->what_happens = isset($config['what_happens']) ? (string)$config['what_happens'] : null;
        $this->webhook_token = isset($config['webhook_token']) ? (string)$config['webhook_token'] : null;
    }

    /**
     * @return array
     */
    public function toArray(): array
    {
        $array = [];

        if ($this->what_happens !== null) {
            $array['what_happens'] = $this->what_happens;
        }

        if ($this->webhook_token !== null) {
            $array['webhook_token'] = $this->webhook_token;
        }

        return $array;
    }

    /**
     * @param string $type The relay type from department_relays_o
     * @throws Exception
     */
    public function validate(string $type): void
    {
        if ($type === 'TRIGGER') {
            if (empty($this->what_happens)) {
                throw new Exception('what_happens is required for TRIGGER relay type');
            }
            if (empty($this->webhook_token)) {
                throw new Exception('webhook_token is required for TRIGGER relay type');
            }
        }
    }
}
