package mgt

import (
	"context"
	"errors"

	"bsm/full/module/ec/order/internal/impl"
	"bsm/full/module/ec/order/internal/logic/common"
	"bsm/full/module/ec/order/internal/models"
	pb "bsm/full/module/ec/order/pb"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"gorm.io/gorm"
)

// 获取一个订单的详情数据
func OrderGet(ctx context.Context, in *pb.OrderIdentRequest) (reply *pb.OrderGetReply, err error) {
	// parse authorization meta.
	RoleValve := &service.ParseOptions{RoleValue: "Mall_Admin"}
	if in.GetAgency() != "" {
		RoleValve = nil
	}
	auth, err := service.ParseMetaCtx(ctx, RoleValve)
	if err != nil {
		return nil, err
	}

	if auth.Owner == nil {
		return nil, errcode.ErrPermissionDenied
	}

	// valildate request id,identity.
	if in.Id == 0 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}
	var storeIdentity string
	if in.GetAgency() != "" {
		storeIdentity = in.GetStoreIdentity()
	} else {
		ownerStore := auth.Owner.(map[string]any)
		storeIdentity = ownerStore["store_identity"].(string)
	}
	order := &models.OrderSummary{}
	err = impl.DBService.Model(&models.OrderSummary{}).Where("store_identity = ? and identity=?", storeIdentity, in.Identity).Preload("OrderDetails").Find(&order).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	data := common.ReflectProtoOrderSummary(order)
	return &pb.OrderGetReply{Summary: data}, nil
}
