package action

import (
	"crm-api/internal/app/ami"
	"crm-api/internal/app/redis"
	"crm-api/pkg/utils"
	"errors"
	"fmt"
)

func DBPut(family, key, value string) (err error) {
	action := map[string]string{
		"Action": "DBPut",
		"Family": family,
		"Key":    key,
		"Val":    value,
	}

	res, _, err := ami.AminInstance.Send(action)
	if err != nil {
		return err
	}
	if res["Response"] != "Success" {
		return errors.New(res["Message"])
	}
	if family == "DND" {
		redis.ExtensionDNDSet(key, value)
		_, _, _ = utils.ExecCmdAsync("asterisk", "-rx", fmt.Sprintf("presencestate change CustomPresence:%s dnd", key))
		_, _, _ = utils.ExecCmdAsync("asterisk", "-rx", fmt.Sprintf("pjsip send notify dndon endpoint %s", key))

	}
	return nil
}

func DBDel(family, key string) error {
	action := map[string]string{
		"Action": "DBDel",
		"Family": family,
		"Key":    key,
	}

	res, _, err := ami.AminInstance.Send(action)
	if err != nil {
		return err
	}
	if res["Response"] != "Success" {
		return errors.New(res["Message"])
	}
	if family == "DND" {
		redis.ExtensionDNDDel(key)
		_, _, _ = utils.ExecCmdAsync("asterisk", "-rx", fmt.Sprintf("presencestate change CustomPresence:%s XA", key))
		_, _, _ = utils.ExecCmdAsync("asterisk", "-rx", fmt.Sprintf("pjsip send notify dndoff endpoint %s", key))
	}
	return nil
}

func DBGet(family, key string) (value string, err error) {
	action := map[string]string{
		"Action": "DBGet",
		"Family": family,
		"Key":    key,
	}

	res, events, err := ami.AminInstance.Send(action)
	if err != nil {
		return "", err
	}
	if res["Response"] != "Success" {
		return "", errors.New(res["Message"])
	}
	for _, v := range events {
		if v.Data["Event"] == "DBGetResponse" {
			return v.Data["Val"], nil
		}
	}
	return "", nil
}
