package disk

import (
	"context"
	"path/filepath"
	"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 MoveDir(ctx context.Context, in *pb.MoveDirRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// validate request
	if in.Id == 0 {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var dir models.CloudDiskDir
	if err := impl.DBService.Where("id = ? AND passport_id = ?", in.Id, auth.ID).First(&dir).Error; err != nil {
		printer.Error("Directory not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 检查目标父目录是否存在
	if in.NewParentId > 0 {
		var parentDir models.CloudDiskDir
		if err := impl.DBService.Where("id = ? AND passport_id = ?", in.NewParentId, auth.ID).First(&parentDir).Error; err != nil {
			printer.Error("Parent directory not found: %v", err)
			return nil, errcode.ErrInvalidArgument
		}

		// 检查是否会形成循环引用
		if dir.ID == parentDir.ID {
			return nil, errcode.ErrInvalidArgument
		}

		// 检查目标路径是否已存在
		newPath := filepath.Join(parentDir.Path, dir.Name)
		var existingDir models.CloudDiskDir
		if err := impl.DBService.Where("path = ? AND passport_id = ? AND id != ?", newPath, auth.ID, dir.ID).First(&existingDir).Error; err == nil {
			return nil, errcode.ErrAlreadyExists
		}

		// 更新目录
		oldPath := dir.Path
		newParentId := uint(in.NewParentId)
		dir.ParentID = &newParentId
		dir.Path = newPath

		if err := impl.DBService.Save(&dir).Error; err != nil {
			printer.Error("Move directory error: %v", err)
			return nil, errcode.ErrDB
		}

		// 更新所有子目录的路径
		var subdirs []models.CloudDiskDir
		if err := impl.DBService.Where("path LIKE ? AND passport_id = ?", oldPath+"%", auth.ID).Find(&subdirs).Error; err == nil {
			for _, subdir := range subdirs {
				newSubPath := strings.Replace(subdir.Path, oldPath, newPath, 1)
				impl.DBService.Model(&subdir).Update("path", newSubPath)
			}
		}
	} else {
		// 移动到根目录
		oldPath := dir.Path
		dir.ParentID = nil
		dir.Path = "/" + dir.Name

		// 检查根目录下是否已存在同名目录
		var existingDir models.CloudDiskDir
		if err := impl.DBService.Where("path = ? AND passport_id = ? AND id != ?", dir.Path, auth.ID, dir.ID).First(&existingDir).Error; err == nil {
			return nil, errcode.ErrAlreadyExists
		}

		if err := impl.DBService.Save(&dir).Error; err != nil {
			printer.Error("Move directory error: %v", err)
			return nil, errcode.ErrDB
		}

		// 更新所有子目录的路径
		var subdirs []models.CloudDiskDir
		if err := impl.DBService.Where("path LIKE ? AND passport_id = ?", oldPath+"%", auth.ID).Find(&subdirs).Error; err == nil {
			for _, subdir := range subdirs {
				newSubPath := strings.Replace(subdir.Path, oldPath, dir.Path, 1)
				impl.DBService.Model(&subdir).Update("path", newSubPath)
			}
		}
	}

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