<?php

// SPDX-FileCopyrightText: 2023 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-3.0-or-later

namespace Icinga\Module\Notifications\Model;

use DateTime;
use Icinga\Module\Notifications\Common\Model;
use ipl\Orm\Behavior\BoolCast;
use ipl\Orm\Behavior\MillisecondTimestamp;
use ipl\Orm\Behaviors;
use ipl\Orm\Query;
use ipl\Orm\Relations;
use ipl\Web\Widget\Icon;

/**
 * @property int $id
 * @property string $name
 * @property string $type
 * @property ?string $config
 * @property DateTime $changed_at
 * @property bool $deleted
 *
 * @property Query|IncidentHistory $incident_history
 * @property Query|RuleEscalationRecipient $rule_escalation_recipient
 * @property Query|Contact $contact
 * @property Query|AvailableChannelType $available_channel_type
 */
class Channel extends Model
{
    public function getTableName(): string
    {
        return 'channel';
    }

    public function getKeyName(): string
    {
        return 'id';
    }

    public function getColumns(): array
    {
        return [
            'name',
            'type',
            'config',
            'changed_at',
            'deleted',
            'external_uuid'
        ];
    }

    public function getColumnDefinitions(): array
    {
        return [
            'name'          => t('Name'),
            'type'          => t('Type'),
            'changed_at'    => t('Changed At'),
            'external_uuid' => t('UUID')
        ];
    }

    public function getSearchColumns(): array
    {
        return ['name'];
    }


    public function getDefaultSort(): array
    {
        return ['name'];
    }

    public function createBehaviors(Behaviors $behaviors): void
    {
        $behaviors->add(new MillisecondTimestamp(['changed_at']));
        $behaviors->add(new BoolCast(['deleted']));
    }

    public function createRelations(Relations $relations): void
    {
        $relations->hasMany('incident_history', IncidentHistory::class)->setJoinType('LEFT');
        $relations->hasMany('rule_escalation_recipient', RuleEscalationRecipient::class)->setJoinType('LEFT');
        $relations->hasMany('contact', Contact::class)
            ->setJoinType('LEFT')
            ->setForeignKey('default_channel_id');
        $relations->belongsTo('available_channel_type', AvailableChannelType::class)
            ->setCandidateKey('type');
    }

    /**
     * Get the channel icon
     *
     * @return Icon
     */
    public function getIcon(): Icon
    {
        return match ($this->type) {
            'rocketchat' => new Icon('comment-dots'),
            'email'      => new Icon('at'),
            default      => new Icon('envelope')
        };
    }
}
