package statemachine

// State 工单状态
type State string

const (
	StatusCreated       State = "created"
	StatusPending       State = "pending"
	StatusAssigned      State = "assigned"
	StatusInProgress    State = "in_progress"
	StatusPendingReview State = "pending_review"
	StatusReturned      State = "returned"
	StatusApproved      State = "approved"
	StatusRejected      State = "rejected"
	StatusRevoked       State = "revoked"
	StatusClosed        State = "closed"
	// 扩展状态 - microservice_update
	StatusExecuting  State = "executing"
	StatusMonitoring State = "monitoring"
	StatusRollbacked State = "rollbacked"
	// 扩展状态 - project_detail
	StatusDraftSaved State = "draft_saved"
)

// Event 转换事件
type Event string

const (
	EventSubmit     Event = "submit"
	EventAutoAssign Event = "auto_assign"
	EventAssign     Event = "assign"
	EventAccept     Event = "accept"
	EventReassign   Event = "reassign"
	EventComplete   Event = "complete"
	EventApprove    Event = "approve"
	EventReject     Event = "reject"
	EventReturn     Event = "return"
	EventResubmit   Event = "resubmit"
	EventRevoke     Event = "revoke"
	EventClose      Event = "close"
	// 扩展事件 - microservice_update
	EventExecute       Event = "execute"
	EventExecuteOK     Event = "execute_ok"
	EventExecuteFail   Event = "execute_fail"
	EventMonitorOK     Event = "monitor_ok"
	EventMonitorFail   Event = "monitor_fail"
	EventRollbackDone  Event = "rollback_done"
	// 扩展事件 - project_detail
	EventSaveDraft     Event = "save_draft"
	EventContinueEdit  Event = "continue_edit"
)

// Transition 状态转换规则
type Transition struct {
	From  State
	Event Event
	To    State
}

// BaseTransitions 基础状态转换规则
var BaseTransitions = []Transition{
	// 创建后流转
	{StatusCreated, EventSubmit, StatusPending},
	{StatusCreated, EventAutoAssign, StatusAssigned},
	{StatusCreated, EventRevoke, StatusRevoked},

	// 待分配流转
	{StatusPending, EventAssign, StatusAssigned},
	{StatusPending, EventRevoke, StatusRevoked},

	// 已分配流转
	{StatusAssigned, EventAccept, StatusInProgress},
	{StatusAssigned, EventReassign, StatusAssigned},
	{StatusAssigned, EventRevoke, StatusRevoked},

	// 处理中流转
	{StatusInProgress, EventComplete, StatusPendingReview},
	{StatusInProgress, EventReturn, StatusReturned},
	{StatusInProgress, EventReassign, StatusAssigned},
	{StatusInProgress, EventRevoke, StatusRevoked},

	// 待审核流转
	{StatusPendingReview, EventApprove, StatusApproved},
	{StatusPendingReview, EventReject, StatusRejected},
	{StatusPendingReview, EventReturn, StatusReturned},
	{StatusPendingReview, EventRevoke, StatusRevoked},

	// 已打回流转
	{StatusReturned, EventResubmit, StatusInProgress},
	{StatusReturned, EventRevoke, StatusRevoked},

	// 终态关闭
	{StatusApproved, EventClose, StatusClosed},
	{StatusRejected, EventClose, StatusClosed},
	{StatusRevoked, EventClose, StatusClosed},
}

// MicroserviceUpdateTransitions 微服务更新扩展转换规则
var MicroserviceUpdateTransitions = []Transition{
	{StatusApproved, EventExecute, StatusExecuting},
	{StatusExecuting, EventExecuteOK, StatusMonitoring},
	{StatusExecuting, EventExecuteFail, StatusRollbacked},
	{StatusMonitoring, EventMonitorOK, StatusClosed},
	{StatusMonitoring, EventMonitorFail, StatusRollbacked},
	{StatusRollbacked, EventRollbackDone, StatusClosed},
}

// ProjectDetailTransitions 项目详情扩展转换规则
var ProjectDetailTransitions = []Transition{
	{StatusInProgress, EventSaveDraft, StatusDraftSaved},
	{StatusDraftSaved, EventContinueEdit, StatusInProgress},
}

// TerminalStates 终态集合
var TerminalStates = map[State]bool{
	StatusApproved: true,
	StatusRejected: true,
	StatusRevoked:  true,
	StatusClosed:   true,
}

// AllTransitions 获取所有转换规则（包含扩展）
func AllTransitions(workflowType string) []Transition {
	transitions := make([]Transition, len(BaseTransitions))
	copy(transitions, BaseTransitions)

	switch workflowType {
	case "microservice_update":
		transitions = append(transitions, MicroserviceUpdateTransitions...)
	case "project_detail":
		transitions = append(transitions, ProjectDetailTransitions...)
	}

	return transitions
}

// CanTransition 检查是否可以转换
func CanTransition(from State, event Event) (State, bool) {
	for _, t := range BaseTransitions {
		if t.From == from && t.Event == event {
			return t.To, true
		}
	}
	return "", false
}

// CanTransitionWithType 检查是否可以转换（带工单类型）
func CanTransitionWithType(from State, event Event, workflowType string) (State, bool) {
	transitions := AllTransitions(workflowType)
	for _, t := range transitions {
		if t.From == from && t.Event == event {
			return t.To, true
		}
	}
	return "", false
}

// IsTerminal 检查是否为终态
func IsTerminal(s State) bool {
	return TerminalStates[s]
}

// CanRevoke 检查是否可撤销
func CanRevoke(s State) bool {
	return !IsTerminal(s)
}

// GetAvailableEvents 获取当前状态可用的事件
func GetAvailableEvents(from State, workflowType string) []Event {
	transitions := AllTransitions(workflowType)
	events := make([]Event, 0)
	seen := make(map[Event]bool)

	for _, t := range transitions {
		if t.From == from && !seen[t.Event] {
			events = append(events, t.Event)
			seen[t.Event] = true
		}
	}

	return events
}

// ValidateTransitionChain 验证转换链是否合法
func ValidateTransitionChain(workflowType string, states []State, events []Event) bool {
	if len(states) != len(events)+1 {
		return false
	}

	for i, event := range events {
		toState, valid := CanTransitionWithType(states[i], event, workflowType)
		if !valid || toState != states[i+1] {
			return false
		}
	}

	return true
}
