package xunji_service

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

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

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

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

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

func (l *GetXunjiServiceByIdLogic) GetXunjiServiceById(req *types.IDReq) (*types.XunjiServiceInfoResp, error) {
	data, err := l.svcCtx.DB.XunjiService.Query().Where(xunjiservice.ID(req.Id)).WithAgent().Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	var agent types.AgentInfo
	if data.Edges.Agent != nil {
		agent = types.AgentInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.AgentID,
				CreatedAt: pointy.GetPointer(data.Edges.Agent.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.Edges.Agent.UpdatedAt.UnixMilli()),
			},
			Name:       &data.Edges.Agent.Name,
			Role:       &data.Edges.Agent.Role,
			Status:     &data.Edges.Agent.Status,
			Background: &data.Edges.Agent.Background,
			Examples:   &data.Edges.Agent.Examples,
		}
	}

	return &types.XunjiServiceInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.XunjiServiceInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:         &data.Status,
			XunjiId:        &data.XunjiID,
			AgentId:        &data.AgentID,
			AgentInfo:      &agent,
			OrganizationId: &data.OrganizationID,
			Wxid:           &data.Wxid,
			ApiBase:        &data.APIBase,
			ApiKey:         &data.APIKey,
		},
	}, nil
}
