package workflow

import (
	"encoding/json"
	"fmt"

	"com.sclktx/m/v2/internal/common/model"
	"gorm.io/gorm"
)

// ApproverResolver 审批人动态解析器
type ApproverResolver struct {
	db *gorm.DB
}

func NewApproverResolver(db *gorm.DB) *ApproverResolver {
	return &ApproverResolver{db: db}
}

// parseJSONIDs 解析 JSON 数组字符串为 uint 切片
func parseJSONIDs(jsonStr string) []uint {
	if jsonStr == "" {
		return nil
	}
	var ids []uint
	if err := json.Unmarshal([]byte(jsonStr), &ids); err != nil {
		return nil
	}
	return ids
}

// ResolveDeptApproverIDs 取部门指定审批人（approver_user_ids），空则返回空切片
func (r *ApproverResolver) ResolveDeptApproverIDs(deptID uint) ([]uint, error) {
	var dept model.Department
	if err := r.db.First(&dept, deptID).Error; err != nil {
		return nil, fmt.Errorf("部门不存在: %w", err)
	}
	return parseJSONIDs(dept.ApproverUserIDs), nil
}

// ResolveVPIDsByDepartment 取部门分管领导（vp_user_ids），空则返回空切片
func (r *ApproverResolver) ResolveVPIDsByDepartment(deptID uint) ([]uint, error) {
	var dept model.Department
	if err := r.db.First(&dept, deptID).Error; err != nil {
		return nil, fmt.Errorf("部门不存在: %w", err)
	}
	return parseJSONIDs(dept.VpUserIDs), nil
}

// GetGlobalApproverIDs 获取所有全局兜底审批人
func (r *ApproverResolver) GetGlobalApproverIDs() ([]uint, error) {
	var approvers []model.GlobalApprover
	r.db.Find(&approvers)
	var ids []uint
	for _, a := range approvers {
		ids = append(ids, a.UserID)
	}
	return ids, nil
}
