package library

import (
	"context"
	"errors"

	"bsm/full/module/ec/address/internal/impl"
	"bsm/full/module/ec/address/internal/models"
	pb "bsm/full/module/ec/address/pb"

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

// 获取一条地址
func Get(ctx context.Context, in *pb.IdentRequest) (reply *pb.AddressItem, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	if in.GetId() == 0 {
		return nil, errcode.ErrInvalidArgument
	}

	address := new(models.AddressLibrary)
	err = impl.DBService.Where("id=?", in.Id).First(&address).Error

	if err != nil {
		if errors.Is(err, models.ErrNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.AddressItem{
		Id:       int64(address.ID),
		Identity: address.Identity,
		Name:     address.Name,
		Phone:    address.Phone,
		Province: address.Province,
		City:     address.City,
		Area:     address.Area,
		Detail:   address.Detail,
		Country:  address.Country,
		Pics:     address.Pics,
		Contact:  address.Contact,
		Status:   int32(address.Status),
	}, nil
}
