<?php

namespace classes;

use Exception;

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

    /**
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $this->type = strtoupper(trim((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;
        $this->relay_id = isset($config['relay_id']) ? trim((string)$config['relay_id']) : null;
        $this->pulse_seconds = isset($config['pulse_seconds']) ? (int)$config['pulse_seconds'] : 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;
        }

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

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

        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');
            }
            return;
        }

        if ($this->type === 'RELAY') {
            if ($this->relay_id === null || $this->relay_id === '') {
                throw new Exception('relay_id is required for RELAY gate type');
            }
            if ($this->pulse_seconds !== null && $this->pulse_seconds < 0) {
                throw new Exception('pulse_seconds must be a positive integer for RELAY gate type');
            }
            return;
        }

        throw new Exception('Unsupported gate config type: ' . $this->type);
    }
}
