package service

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

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

	bizReply, err := c.queryProduct(ctx, request)
	if err != nil {
		return c.QueryProductFail(ctx, err)
	}

	return c.QueryProductSuccess(ctx, bizReply)
}

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

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

	return c.VoucherBiz.CmbProductQuery(ctx, bizContent.ActivityId)
}

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

	replyBizContent, _ := json.Marshal(bizReply)

	return c.GetResponse(ctx, replyBizContent)
}

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

	se := errors.FromError(err)

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

	log.Errorf("query product fail: %v", se)

	bizReply := &v1.CmbQueryProductReply{
		RespCode:     vo.CmbResponseStatusFail.GetValue(),
		RespMsg:      se.Message,
		ThirdErrCode: se.Reason,
	}

	replyBizContent, _ := json.Marshal(bizReply)

	return c.GetResponse(ctx, replyBizContent)
}
