package disk

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 ListDirs(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListDirsResponse, 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 dirs []models.CloudDiskDir
	var total int64

	// 获取总数
	if err := impl.DBService.Model(&models.CloudDiskDir{}).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).
		Preload("Parent").
		Order("created_at DESC").
		Offset(int(offset)).
		Limit(int(in.PageSize)).
		Find(&dirs).Error; err != nil {
		return nil, err
	}

	// 转换数据
	var dirItems []*pb.CloudDiskDirItem
	for _, dir := range dirs {
		var parentId uint64
		if dir.ParentID != nil {
			parentId = uint64(*dir.ParentID)
		}

		var parent *pb.CloudDiskDirItem
		if dir.Parent != nil {
			parent = &pb.CloudDiskDirItem{
				Id:        uint64(dir.Parent.ID),
				Identity:  dir.Parent.Identity,
				Name:      dir.Parent.Name,
				Path:      dir.Parent.Path,
				CreatedAt: dir.Parent.CreatedAt.Format(time.RFC3339),
				UpdatedAt: dir.Parent.UpdatedAt.Format(time.RFC3339),
			}
		}

		dirItems = append(dirItems, &pb.CloudDiskDirItem{
			Id:        uint64(dir.ID),
			Identity:  dir.Identity,
			ParentId:  parentId,
			Name:      dir.Name,
			Path:      dir.Path,
			CreatedAt: dir.CreatedAt.Format(time.RFC3339),
			UpdatedAt: dir.UpdatedAt.Format(time.RFC3339),
			Parent:    parent,
		})
	}

	reply = &pb.ListDirsResponse{
		Dirs:  dirItems,
		Total: total,
	}

	return reply, nil
}
