package controllers

import (
	"github.com/gogf/gf/util/guid"
	"github.com/kataras/iris/v12"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"
)

// SceneHistoryRequest scene-service saveHis 请求体
type SceneHistoryRequest struct {
	SceneId     string `json:"scene_id"`
	ConditionId string `json:"condition_id"`
	ActionId    string `json:"action_id"`
}

// SceneHistoryHandler 场景历史内部接口处理器
// 供 scene-service 通过 HTTP POST 调用，无需JWT认证
type SceneHistoryHandler struct {
	Ctx     iris.Context
	Service services.SceneHisService
}

// Post 保存场景执行历史
// POST /iot/v1/scene_history
func (a *SceneHistoryHandler) Post() {
	req := new(SceneHistoryRequest)
	if err := a.Ctx.ReadJSON(req); err != nil {
		fail(a.Ctx, iris.StatusBadRequest, "请求参数错误:%s", err.Error())
		return
	}

	if req.SceneId == "" {
		fail(a.Ctx, iris.StatusBadRequest, "scene_id不能为空")
		return
	}

	sceneHis := &models.SceneHis{
		RecordId:    guid.S(),
		SceneID:     req.SceneId,
		ConditionId: req.ConditionId,
		ActionId:    req.ActionId,
	}

	err := a.Service.Create(sceneHis)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, sceneHis)
}
