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/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
)

// 获取目录树
func GetDirTree(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudDiskDirItem, 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 dir models.CloudDiskDir
	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.Preload("Parent").Preload("Subdirectories").Preload("Files").First(&dir).Error; err != nil {
		printer.Error("Directory not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 递归加载子目录树
	var loadSubdirs func(*models.CloudDiskDir) []*pb.CloudDiskDirItem
	loadSubdirs = func(d *models.CloudDiskDir) []*pb.CloudDiskDirItem {
		var subdirs []*pb.CloudDiskDirItem
		for _, subdir := range d.Subdirectories {
			subdirItem := &pb.CloudDiskDirItem{
				Id:             uint64(subdir.ID),
				Identity:       subdir.Identity,
				ParentId:       uint64(*subdir.ParentID),
				Name:           subdir.Name,
				Path:           subdir.Path,
				CreatedAt:      subdir.CreatedAt.Format(time.RFC3339),
				UpdatedAt:      subdir.UpdatedAt.Format(time.RFC3339),
				Subdirectories: loadSubdirs(&subdir),
			}
			subdirs = append(subdirs, subdirItem)
		}
		return subdirs
	}

	// 转换文件数据
	var files []*pb.CloudDiskFileItem
	for _, file := range dir.Files {
		files = append(files, &pb.CloudDiskFileItem{
			Id:           uint64(file.ID),
			Identity:     file.Identity,
			DirectoryId:  uint64(*file.DirectoryID),
			Name:         file.Name,
			OriginalName: file.OriginalName,
			Size:         file.Size,
			MimeType:     file.MimeType,
			StoragePath:  file.StoragePath,
			Hash:         file.Hash,
			CreatedAt:    file.CreatedAt.Format(time.RFC3339),
			UpdatedAt:    file.UpdatedAt.Format(time.RFC3339),
		})
	}

	// 构建父目录信息
	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),
		}
	}

	reply = &pb.CloudDiskDirItem{
		Id:             uint64(dir.ID),
		Identity:       dir.Identity,
		ParentId:       uint64(*dir.ParentID),
		Name:           dir.Name,
		Path:           dir.Path,
		CreatedAt:      dir.CreatedAt.Format(time.RFC3339),
		UpdatedAt:      dir.UpdatedAt.Format(time.RFC3339),
		Parent:         parent,
		Subdirectories: loadSubdirs(&dir),
		Files:          files,
	}

	return reply, nil
}
