<?php

namespace classes;

use Exception;

class department_gate_config
{
    public string $type;
    public ?string $phone_number = null;
    public ?int $call_duration_threshold = null;

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

    /**
     * @return array
     */
    public function toArray(): array
    {
        $array = [
            'type' => $this->type,
        ];

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

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

        return $array;
    }

    /**
     * @throws Exception
     * @description Valid example: ["type" => "PHONE_CALL", "phone_number" => "+1234567890", "call_duration_threshold" => 30]
     * @description Valid example 2: {"type":"PHONE_CALL","phone_number":"+1234567890","call_duration_threshold":30}
     */
    public function validate(): void
    {
        if (empty($this->type)) {
            throw new Exception('Gate config type cannot be empty');
        }

        if ($this->type === 'PHONE_CALL') {
            if (empty($this->phone_number)) {
                throw new Exception('Phone number is required for PHONE_CALL gate type');
            }
            if ($this->call_duration_threshold === null) {
                throw new Exception('Call duration threshold is required for PHONE_CALL gate type');
            }
        }
    }
}
