package database

import (
	"log"

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

// InitData 初始化基础数据
func InitData(db *gorm.DB) {
	initProcessDefinitions(db)
}

func initProcessDefinitions(db *gorm.DB) {
	defs := []model.ProcessDefinition{
		{
			ProcessName: "访客预约审批",
			ProcessCode: "visitor_approval",
			Source:      "访客系统",
			Description: "访客预约三级审批：公司接待员工 → 部门指定人 → 分管领导",
			IsActive:    true,
			NodesJSON: `[
      {"node_id":"Start","node_name":"发起预约","node_type":0,"user_ids":["$starter"]},
      {"node_id":"Employee","node_name":"公司接待员工审批","node_type":1,"prev_node_ids":["Start"],"user_ids":["$employee_id"]},
      {"node_id":"DeptApprover","node_name":"部门指定人审批","node_type":1,"prev_node_ids":["Employee"],"user_ids":["$dept_approver_ids"]},
      {"node_id":"VPApproval","node_name":"分管领导审批","node_type":1,"prev_node_ids":["DeptApprover"],"user_ids":["$vp_ids"]},
      {"node_id":"End","node_name":"审批完成","node_type":3,"prev_node_ids":["VPApproval"]}
    ]`,
		},
		{
			ProcessName: "访客预约审批（兜底）",
			ProcessCode: "visitor_approval_simple",
			Source:      "访客系统",
			Description: "访客预约兜底审批：直接推送给全局兜底审批人",
			IsActive:    true,
			NodesJSON: `[
      {"node_id":"Start","node_name":"发起预约","node_type":0,"user_ids":["$starter"]},
      {"node_id":"DefaultApproval","node_name":"兜底审批","node_type":1,"prev_node_ids":["Start"],"user_ids":["$default_approver_ids"]},
      {"node_id":"End","node_name":"审批完成","node_type":3,"prev_node_ids":["DefaultApproval"]}
    ]`,
		},
	}

	for _, def := range defs {
		var count int64
		db.Model(&model.ProcessDefinition{}).Where("process_code = ?", def.ProcessCode).Count(&count)
		if count > 0 {
			log.Printf("[init] 流程定义已存在，跳过: %s", def.ProcessCode)
			continue
		}
		if err := db.Create(&def).Error; err != nil {
			log.Printf("[init] 创建流程定义失败 %s: %v", def.ProcessCode, err)
		} else {
			log.Printf("[init] 创建流程定义成功: %s", def.ProcessCode)
		}
	}
}
