package operation

import (
	"time"

	"github.com/tidbcloud/devops/models/base"
)

type OperationInstanceAction struct {
	base.Updatable

	Order           int        `gorm:"not null"`
	Name            string     `gorm:"type:VARCHAR(255);not null"`
	Type            string     `gorm:"type:VARCHAR(255);not null"`
	StartPolicy     string     `gorm:"type:VARCHAR(255);not null"`
	StartScheduleAt *time.Time `gorm:"type:TIMESTAMP"`

	// status
	StartedAt  *time.Time `gorm:"type:TIMESTAMP"`
	FinishedAt *time.Time `gorm:"type:TIMESTAMP"`
	Status     string     `gorm:"type:VARCHAR(255);not null"`
	Output     string     `gorm:"type:VARCHAR(2048)"`

	// association
	InstanceID uint64 `gorm:"index:idx_instance_id;not null"`
}

func (OperationInstanceAction) TableName() string {
	return "operation_instance_actions"
}

type OperationInstance struct {
	base.Updatable

	Type           string `gorm:"type:VARCHAR(255);not null"`
	Operation      string `gorm:"type:VARCHAR(255);not null"`
	Reason         string `gorm:"type:VARCHAR(1024)"`
	Params         []byte `gorm:"type:JSON"`
	Outputs        []byte `gorm:"type:JSON"`
	Applicant      string `gorm:"type:VARCHAR(255);not null"` // email
	OperatorEntity string `gorm:"type:VARCHAR(255)"`

	ExecutionWindowID *uint64 `gorm:"column:execution_window_id"`

	// status
	Phase      string     `gorm:"type:VARCHAR(255);index:idx_phase;not null"`
	ApprovalID *uint64    `gorm:"index:idx_approval_id"`
	ClosedAt   *time.Time `gorm:"type:TIMESTAMP"`

	// association
	Actions  []*OperationInstanceAction        `gorm:"foreignkey:InstanceID"`
	ToTarget *OperationInstanceToTargetMapping `gorm:"foreignkey:InstanceID"` // build when convert entity to model
}

func (OperationInstance) TableName() string {
	return "operation_instances"
}

type OperationInstanceToTargetMapping struct {
	InstanceID uint64 `gorm:"primary_key;not null"`
	TargetType string `gorm:"type:VARCHAR(255);index:idx_target;not null"`
	TargetID   string `gorm:"type:VARCHAR(255);index:idx_target;not null"`
}

func (OperationInstanceToTargetMapping) TableName() string {
	return "operation_instance_to_target_mappings"
}
