package cpa

import (
	"strings"

	"ops-assistant/internal/core/command"
	"ops-assistant/internal/core/ecode"
	coremodule "ops-assistant/internal/core/module"
	"ops-assistant/internal/core/runbook"
	"gorm.io/gorm"
)

type Module struct {
	db     *gorm.DB
	exec   *runbook.Executor
	runner *coremodule.Runner
}

func New(db *gorm.DB, exec *runbook.Executor) *Module {
	return &Module{db: db, exec: exec, runner: coremodule.NewRunner(db, exec)}
}

func (m *Module) Handle(userID int64, cmd *command.ParsedCommand) (string, error) {
	text := strings.TrimSpace(cmd.Raw)
	if text == "/cpa" || strings.HasPrefix(text, "/cpa help") {
		return "CPA 模块\n- /cpa status\n- /cpa usage backup\n- /cpa usage restore <backup_id> [--confirm YES_RESTORE] [--dry-run]", nil
	}
	specs := commandSpecs()
	if sp, ok := coremodule.MatchCommand(text, specs); ok {
		jobID, out, err := coremodule.ExecTemplate(m.runner, userID, cmd.Raw, sp.Template)
		if err != nil {
			return formatErr(ecode.ErrStepFailed, coremodule.FormatExecError(sp, err)), nil
		}
		if out == "dry-run" {
			return formatOK(coremodule.FormatDryRunMessage(sp.Template)), nil
		}
		return formatOK(coremodule.FormatSuccessMessage(sp.Template, jobID)), nil
	}
	return "❓ 暂不支持该 CPA 命令。当前支持：/cpa status, /cpa usage backup, /cpa usage restore <backup_id>", nil
}
