package entity

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"time"
)

type NotificationActionExecInfo struct {
	ID             uint      `gorm:"primaryKey"`
	CreatedTime    time.Time `gorm:"type:timestamp"`
	FinishedTime   time.Time `gorm:"type:timestamp"`
	NotificationID uint
	Notification   *Notification      `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
	Action         NotificationAction `gorm:"type:text"`
	Done           uint
}

const (
	ActionStatusPending = 0
	ActionStatusTrue    = 1
	ActionStatusFalse   = 2
	ActionStatusError   = 3
	// ActionStatusSkipped: never run because another system owns it. Not a
	// failure, and nothing should retry it.
	ActionStatusSkipped = 4
)

type NotificationAction struct {
	Cmd          []string `yaml:"cmd"`
	LogOnComment bool     `yaml:"log_on_comment"`
	OnSuccess    string   `yaml:"on_success"`
	OnFailure    string   `yaml:"on_failure"`
	OnError      string   `yaml:"on_error"`
}

// read NotificationAction of json string format from database
func (a *NotificationAction) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("unsupported value: %v", value)
	}

	result := NotificationAction{}

	err := json.Unmarshal(bytes, &result)
	*a = result
	return err
}

// store NotificationAction as json string in database
func (a NotificationAction) Value() (driver.Value, error) {
	b, err := json.Marshal(a)
	if err != nil {
		return nil, err
	}
	s := string(b)
	return s, err
}
