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

// 移动文件
func MoveFile(ctx context.Context, in *pb.MoveFileRequest) (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 file models.CloudDiskFile
	if err := impl.DBService.Joins("JOIN cloud_disk_dirs ON cloud_disk_files.directory_id = cloud_disk_dirs.id").
		Where("cloud_disk_files.id = ? AND cloud_disk_dirs.passport_id = ?", in.Id, auth.ID).
		First(&file).Error; err != nil {
		printer.Error("File not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 检查目标目录是否存在且属于当前用户
	var targetDir models.CloudDiskDir
	if err := impl.DBService.Where("id = ? AND passport_id = ?", in.NewDirectoryId, auth.ID).First(&targetDir).Error; err != nil {
		printer.Error("Target directory not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

	// 检查目标目录下是否已存在同名文件
	var existingFile models.CloudDiskFile
	if err := impl.DBService.Where("name = ? AND directory_id = ? AND id != ?", file.Name, in.NewDirectoryId, file.ID).First(&existingFile).Error; err == nil {
		return nil, errcode.ErrAlreadyExists
	}

	// 更新文件目录
	newDirectoryId := uint(in.NewDirectoryId)
	file.DirectoryID = &newDirectoryId

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

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