package disk

import (
	"context"
	"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/types"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 复制文件
func CopyFile(ctx context.Context, in *pb.CopyFileRequest) (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
	}
	if strings.TrimSpace(in.NewName) == "" {
		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.TargetDirectoryId, 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 = ?", in.NewName, in.TargetDirectoryId).First(&existingFile).Error; err == nil {
		return nil, errcode.ErrAlreadyExists
	}

	// 创建文件副本
	newFile := models.CloudDiskFile{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
		},
		CloudBase: models.CloudBase{
			CloudID:       file.CloudID,
			CloudIdentity: file.CloudIdentity,
		},
		DirectoryID:  func() *uint { id := uint(in.TargetDirectoryId); return &id }(),
		Name:         in.NewName,
		OriginalName: in.NewName,
		Size:         file.Size,
		MimeType:     file.MimeType,
		StoragePath:  file.StoragePath, // 注意：实际存储中可能需要复制文件内容
		Hash:         file.Hash,
	}

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

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