package share

import (
	"context"
	"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"
)

// 获取分享详情
func GetShare(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudShareItem, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request id,identity.
	if in.Id == 0 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var share models.CloudShare
	query := impl.DBService.Where("passport_id = ?", auth.ID)

	if in.Id > 0 {
		query = query.Where("id = ?", in.Id)
	} else {
		query = query.Where("identity = ?", in.Identity)
	}

	if err := query.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
	}

	reply = &pb.CloudShareItem{
		Id:            uint64(share.ID),
		Identity:      share.Identity,
		ShareType:     share.ShareType,
		ResourceId:    uint64(share.ResourceID),
		ShareToken:    share.ShareToken,
		Password:      share.Password,
		ExpiresAt:     share.ExpiresAt.Format(time.RFC3339),
		ViewCount:     int32(share.ViewCount),
		DownloadCount: int32(share.DownloadCount),
		IsPublic:      share.IsPublic,
		CreatedAt:     share.CreatedAt.Format(time.RFC3339),
		UpdatedAt:     share.UpdatedAt.Format(time.RFC3339),
	}

	return reply, nil
}
