package system

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/frame/g"
	"server/internal/dao"
	"server/internal/model"
	"server/internal/service"
)

type sSystem struct {
}

func init() {
	service.RegisterSystem(New())
}
func New() service.ISystem {
	return &sSystem{}
}
func (*sSystem) Unique(ctx context.Context, in *model.SystemUniqueInput) (*model.SystemOutput, error) {
	orm := dao.System.Ctx(ctx)
	if in.Key != "" {
		orm = orm.Where("`key`=?", in.Key)
	}
	if in.Lock {
		orm = orm.LockUpdate()
	}
	out := (*model.SystemOutput)(nil)
	err := orm.Scan(&out)
	return out, err
}
func (s *sSystem) Version(ctx context.Context) (*model.SystemVersionOutput, error) {
	system, err := s.Unique(ctx, &model.SystemUniqueInput{
		Key: "version",
	})
	if err != nil {
		return nil, err
	}
	var out *model.SystemVersionOutput
	err = json.Unmarshal([]byte(system.Value), &out)
	return out, err
}

func (s *sSystem) Save(ctx context.Context, in *model.SystemSaveInput) (err error) {
	_, err = dao.System.Ctx(ctx).Update(g.Map{
		"value": in.Value,
	}, g.Map{"key": in.Key})
	return
}
