package workflow

import (
	"context"
	"fmt"
	"time"
)

// =====================================================
// 接口定义（由 rmdc-core 在初始化时注入）
// =====================================================

// UserStatusUpdater 用户状态更新接口
// 由工单模块调用，用于处理工单状态变更后的用户操作
type UserStatusUpdater interface {
	// ActivateUser 激活用户（注册工单审批通过）
	ActivateUser(userID int64) error

	// DeletePendingUser 删除待审批用户（工单撤销时，仅删除 status=disabled 的用户）
	DeletePendingUser(userID int64) error

	// ExecuteUserManagement 执行用户管理操作（管理工单审批通过）
	ExecuteUserManagement(userID int64, action string, payload map[string]interface{}) error
}

// WorkflowCreator 工单创建接口
// 由用户模块调用，用于创建用户注册/管理工单
type WorkflowCreator interface {
	// CreateRegistrationWorkflow 创建用户注册工单
	CreateRegistrationWorkflow(ctx context.Context, req *RegistrationWorkflowRequest) (string, error)

	// CreateManagementWorkflow 创建用户管理工单
	CreateManagementWorkflow(ctx context.Context, req *ManagementWorkflowRequest) (string, error)
}

// =====================================================
// 工单载荷结构
// =====================================================

// RegistrationWorkflowRequest 注册工单请求
type RegistrationWorkflowRequest struct {
	TargetUserID       int64     `json:"target_user_id"`
	TargetUsername     string    `json:"target_username"`
	TargetRole         string    `json:"target_role"`
	RegisteredByID     int64     `json:"registered_by_id"`
	RegisteredByName   string    `json:"registered_by_name"`
	AccountExpiresAt   time.Time `json:"account_expires_at"`
	RegistrationReason string    `json:"registration_reason"`
}

// ManagementWorkflowRequest 管理工单请求
type ManagementWorkflowRequest struct {
	TargetUserID   int64                  `json:"target_user_id"`
	TargetUsername string                 `json:"target_username"`
	ActionType     string                 `json:"action_type"` // update/enable/disable/delete/reset_password/extend_validity
	OperatorID     int64                  `json:"operator_id"`
	OperatorName   string                 `json:"operator_name"`
	OriginalData   map[string]interface{} `json:"original_data"`
	ModifiedData   map[string]interface{} `json:"modified_data"`
	Reason         string                 `json:"reason"`
}

// =====================================================
// UserStatusUpdater 实现示例
// =====================================================

type userStatusUpdaterImpl struct {
	userService *UserService
}

func NewUserStatusUpdater(userService *UserService) UserStatusUpdater {
	return &userStatusUpdaterImpl{userService: userService}
}

// ActivateUser 激活用户（注册工单审批通过时调用）
func (u *userStatusUpdaterImpl) ActivateUser(userID int64) error {
	return u.userService.UpdateUserStatus(userID, "active")
}

// DeletePendingUser 删除待审批用户（工单撤销时调用）
func (u *userStatusUpdaterImpl) DeletePendingUser(userID int64) error {
	// 安全检查：只删除 status=disabled 的用户
	user, err := u.userService.GetUserByID(userID)
	if err != nil {
		return err
	}
	if user.Status != "disabled" {
		return fmt.Errorf("cannot delete user with status: %s", user.Status)
	}
	return u.userService.DeleteUser(userID)
}

// ExecuteUserManagement 执行用户管理操作（管理工单审批通过时调用）
func (u *userStatusUpdaterImpl) ExecuteUserManagement(
	userID int64,
	action string,
	payload map[string]interface{},
) error {
	switch action {
	case "update":
		return u.userService.UpdateUserInfo(userID, payload)
	case "enable":
		return u.userService.UpdateUserStatus(userID, "active")
	case "disable":
		return u.userService.UpdateUserStatus(userID, "disabled")
	case "delete":
		return u.userService.DeleteUser(userID)
	case "reset_password":
		return u.userService.ResetPassword(userID)
	case "extend_validity":
		newExpiresAt, ok := payload["new_expires_at"].(time.Time)
		if !ok {
			return fmt.Errorf("invalid new_expires_at in payload")
		}
		return u.userService.ExtendValidity(userID, newExpiresAt)
	default:
		return fmt.Errorf("unknown action: %s", action)
	}
}

// =====================================================
// rmdc-core 初始化时的注入示例
// =====================================================

func initializeModules() {
	// 创建服务实例
	userService := NewUserService(db)
	workflowService := NewWorkflowService(db)

	// 1. 将用户状态更新器注入到工单模块
	userStatusUpdater := NewUserStatusUpdater(userService)
	workflowService.SetUserStatusUpdater(userStatusUpdater)

	// 2. 将工单创建器注入到用户模块
	workflowCreator := NewWorkflowCreator(workflowService)
	userService.SetWorkflowCreator(workflowCreator)
}

// =====================================================
// 工单状态回调处理
// =====================================================

// HandleUserRegistrationCallback 处理用户注册工单回调
func (s *WorkflowService) HandleUserRegistrationCallback(
	workflowID string,
	event string, // approve/return/revoke
	payload map[string]interface{},
) error {
	userID := payload["target_user_id"].(int64)

	switch event {
	case "approve":
		// 激活用户
		return s.userStatusUpdater.ActivateUser(userID)
	case "return":
		// 打回，用户状态保持 disabled，前端通知用户修改
		return nil
	case "revoke":
		// 撤销，删除待审批用户
		return s.userStatusUpdater.DeletePendingUser(userID)
	default:
		return fmt.Errorf("unknown event: %s", event)
	}
}

// HandleUserManagementCallback 处理用户管理工单回调
func (s *WorkflowService) HandleUserManagementCallback(
	workflowID string,
	event string,
	payload map[string]interface{},
) error {
	userID := payload["target_user_id"].(int64)
	action := payload["action_type"].(string)

	switch event {
	case "approve":
		// 执行管理操作
		return s.userStatusUpdater.ExecuteUserManagement(userID, action, payload)
	case "return":
		// 打回，不执行操作
		return nil
	default:
		return fmt.Errorf("unknown event: %s", event)
	}
}
