package xunji

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent"
	"wechat-api/ent/xunji"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetXunjiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetXunjiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetXunjiLogic {
	return &GetXunjiLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetXunjiLogic) GetXunji() (resp *types.XunjiInfoResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	data, err := l.svcCtx.DB.Xunji.Query().Where(
		xunji.OrganizationID(organizationId),
	).Order(ent.Desc(xunji.FieldCreatedAt)).First(l.ctx)
	if err != nil {
		// 如果记录为空则插入一条默认值的记录
		if ent.IsNotFound(err) {
			_, err = l.svcCtx.DB.Xunji.Create().
				SetStatus(2).
				SetOrganizationID(organizationId).
				Save(l.ctx)
			if err != nil {
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
			}
			data, _ = l.svcCtx.DB.Xunji.Query().Where(
				xunji.OrganizationID(organizationId),
			).Order(ent.Desc(xunji.FieldCreatedAt)).First(l.ctx)
		} else {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, nil)
		}
	}

	return &types.XunjiInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.XunjiInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:         &data.Status,
			AppKey:         &data.AppKey,
			AppSecret:      &data.AppSecret,
			Token:          &data.Token,
			EncodingKey:    &data.EncodingKey,
			OrganizationId: &data.OrganizationID,
		},
	}, nil
}
