package store

import (
	"context"
	"strings"
	"time"

	"bsm/full/module/ec/mall/internal/impl"
	"bsm/full/module/ec/mall/internal/models"
	pb "bsm/full/module/ec/mall/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
)

// 店铺许可授权
func Licensing(ctx context.Context, in *pb.LicensingRequest) (reply *pb.StatusReply, err error) {
	var identity string
	licenseType := strings.ToUpper(in.GetLicenseType())

	switch licenseType {
	case "DOMAIN":
		identity, err = LicensingDomain(in.Domain)
	default:
		return nil, errcode.ErrInvalidArgument
	}
	// TODO: valid code
	if identity == "" {
		return nil, errcode.ErrNotFound(404, "store not found")
	}

	// TODO: add your logic code & delete this line.

	return &pb.StatusReply{
		Code:     0,
		Message:  "OK",
		Identity: identity,
		Timeseq:  time.Now().UnixMilli(),
	}, nil

}

func LicensingDomain(domain string) (string, error) {
	var store models.MallStore
	err := impl.DBService.Model(&models.MallStore{}).Where("subdomain=?", domain).First(&store).Error
	if err != nil {
		return "", err
	}

	return store.Identity, nil
}
