package share

import (
	"context"
	"strings"
	"time"

	"bsm/full/module/base/cloud/internal/impl"
	"bsm/full/module/base/cloud/internal/models"
	pb "bsm/full/module/base/cloud/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 创建分享
func CreateShare(ctx context.Context, in *pb.CreateShareRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// valid code
	if strings.TrimSpace(in.ShareType) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if in.ResourceId == 0 {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.CloudIdentity) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	// 生成分享令牌（如果未提供）
	shareToken := in.ShareToken
	if shareToken == "" {
		shareToken = utils.UUID()
	}

	// 解析过期时间
	var expiresAt time.Time
	if in.ExpiresAt != "" {
		if t, err := time.Parse(time.RFC3339, in.ExpiresAt); err == nil {
			expiresAt = t
		} else {
			expiresAt = time.Now().Add(7 * 24 * time.Hour) // 默认7天过期
		}
	} else {
		expiresAt = time.Now().Add(7 * 24 * time.Hour) // 默认7天过期
	}

	record := models.CloudShare{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
		},
		Std_Passport: types.Std_Passport{
			PassportID:       auth.ID,
			PassportIdentity: auth.Identity,
		},
		CloudBase: models.CloudBase{
			CloudID:       uint(in.CloudId),
			CloudIdentity: in.CloudIdentity,
		},
		ShareType:     in.ShareType,
		ResourceID:    uint(in.ResourceId),
		ShareToken:    shareToken,
		Password:      in.Password,
		ExpiresAt:     expiresAt,
		ViewCount:     0,
		DownloadCount: 0,
		IsPublic:      in.IsPublic,
	}

	if err := impl.DBService.Create(&record).Error; err != nil {
		printer.Error("Create share error: %v", err)
		return nil, errcode.ErrDB
	}

	return &pb.StatusReply{
		Details: record.Identity,
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
