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/vars"
)

// 验证分享密码
func ValidateSharePassword(ctx context.Context, in *pb.ValidateSharePasswordRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if strings.TrimSpace(in.Identity) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var share models.CloudShare
	if err := impl.DBService.Where("identity = ?", in.Identity).First(&share).Error; err != nil {
		printer.Error("Share not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 检查是否过期
	if time.Now().After(share.ExpiresAt) {
		return nil, errcode.ErrInvalidArgument
	}

	// 检查密码（如果设置了密码）
	if share.Password != "" && share.Password != in.Password {
		return nil, errcode.ErrInvalidArgument
	}

	// 增加浏览次数
	share.ViewCount++
	if err := impl.DBService.Save(&share).Error; err != nil {
		printer.Error("Update view count error: %v", err)
		// 不返回错误，继续执行
	}

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