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 UpdateDir(ctx context.Context, in *pb.CloudDiskDirItem) (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 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Name) == "" {
		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.First(&dir).Error; err != nil {
		printer.Error("Directory not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 更新目录名称和路径
	oldPath := dir.Path
	dir.Name = in.Name

	// 重新构建路径
	if dir.ParentID != nil {
		var parentDir models.CloudDiskDir
		if err := impl.DBService.Where("id = ?", *dir.ParentID).First(&parentDir).Error; err == nil {
			dir.Path = filepath.Join(parentDir.Path, in.Name)
		}
	} else {
		dir.Path = "/" + in.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("Update directory error: %v", err)
		return nil, errcode.ErrDB
	}

	// 更新所有子目录的路径
	if oldPath != dir.Path {
		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
}
