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

// 获取分享列表
func ListShares(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListSharesResponse, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request page_no,page_size.
	if in.GetPageNo() < 1 {
		in.PageNo = 1
	}
	if in.GetPageSize() < 10 {
		in.PageSize = 50
	}

	// logic code
	var shares []models.CloudShare
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudShare{}).Where("passport_id = ?", auth.ID).Count(&total).Error; err != nil {
		return nil, err
	}

	// 分页查询
	offset := (in.PageNo - 1) * in.PageSize
	if err := impl.DBService.Where("passport_id = ?", auth.ID).
		Order("created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&shares).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var shareItems []*pb.CloudShareItem
	for _, share := range shares {
		shareItems = append(shareItems, &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),
		})
	}

	reply = &pb.ListSharesResponse{
		Shares: shareItems,
		Total:  total,
	}

	return reply, nil
}
