package service

import (
	"context"
	"encoding/json"
	"github.com/go-kratos/kratos/v2/errors"
	err2 "voucher/api/err"
	v1 "voucher/api/v1"
)

func (c *CmbService) Query(ctx context.Context, request *v1.CmbRequest) (*v1.CmbReply, error) {

	orderNo, err := c.query(ctx, request)

	if err != nil {
		return c.QueryFail(ctx, err)
	}

	return c.QuerySuccess(ctx, orderNo)
}

func (c *CmbService) query(ctx context.Context, request *v1.CmbRequest) (*v1.CmbQueryReply, error) {

	bizContent, err := c.CmbMixRepo.QueryVerify(ctx, request)
	if err != nil {
		return nil, err
	}

	return c.VoucherBiz.CmbQuery(ctx, bizContent.CodeNo)
}

func (c *CmbService) QuerySuccess(ctx context.Context, bizReply *v1.CmbQueryReply) (*v1.CmbReply, error) {

	replyBizContent, _ := json.Marshal(bizReply)

	return c.GetResponse(ctx, replyBizContent)
}

func (c *CmbService) QueryFail(ctx context.Context, err error) (*v1.CmbReply, error) {

	se := errors.FromError(err)

	if len(se.Reason) == 0 {
		se.Reason = err2.CmbErr_CMB_UNKNOWN.String()
	}

	bizReply := &v1.CmbQueryReply{}

	replyBizContent, _ := json.Marshal(bizReply)

	return c.GetResponse(ctx, replyBizContent)
}
