package logic

import (
	"chainweaver.org.cn/chainweaver/did/did-mgr-common-service/internal/config"
	"chainweaver.org.cn/chainweaver/did/did-mgr-common-service/internal/svc"
	"chainweaver.org.cn/chainweaver/did/did-mgr-common-service/internal/types"
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
)

const DIdGetDocumentUrl = "/api/v1/did/document/list"

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

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

type getDocumentReq struct {
	Did []string `json:"did,omitempty,optional"`
}

type document struct {
	Document []*types.GetDocumentResp `json:"document"`
}

type getDocumentResp struct {
	Code int       `json:"code"`
	Msg  string    `json:"msg"`
	Data *document `json:"data"`
}

func (l *GetDocumentLogic) GetDocument(req *types.GetDocumentReq) (resp *types.CommonResp, err error) {
	resp = &types.CommonResp{
		Code: types.SucceedCode,
		Msg:  types.SucceedMsg,
	}
	documentReq := &getDocumentReq{
		Did: []string{req.Did},
	}
	proxy := config.ConfigIns.Service.DidProxy
	targetUrl := config.ConfigIns.Service.Did + DIdGetDocumentUrl
	param, _ := json.Marshal(documentReq)
	respBz, err := DidServerReq(targetUrl, http.MethodPost, proxy, param)
	// todo 返回resp.Msg增加错误日志
	if err != nil {
		resp.Code = types.ErrorDidServerCode
		resp.Msg = types.ErrorDidServerMsg + err.Error()
		return
	}

	// todo 使用"chainweaver.org.cn/chainweaver/did/core"
	respDid := &getDocumentResp{}
	err = json.Unmarshal(respBz, respDid)
	if err != nil || respDid.Data == nil {
		resp.Code = types.ErrorDidServerCode
		resp.Msg = types.ErrorDidServerMsg
		return
	}
	if int32(respDid.Code) != types.SucceedCode {
		resp.Code = types.ErrorDidServerCode
		resp.Msg = types.ErrorDidServerMsg
		resp.Data = respDid
		return
	}

	if respDid.Data == nil {
		resp.Code = types.ErrorGetDocumentCode
		resp.Msg = types.ErrorGetDocumentMsg
		return
	}

	for _, doc := range respDid.Data.Document {
		if doc.Id == req.Did {
			resp.Data = doc
			return
		}
	}

	resp.Code = types.ErrorGetDocumentCode
	resp.Msg = types.ErrorGetDocumentMsg
	return
}