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/vars"
)

// 更新文件
func UpdateFile(ctx context.Context, in *pb.CloudDiskFileItem) (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 file models.CloudDiskFile
	query := impl.DBService.Joins("JOIN cloud_disk_dirs ON cloud_disk_files.directory_id = cloud_disk_dirs.id").
		Where("cloud_disk_dirs.passport_id = ?", auth.ID)

	if in.Id > 0 {
		query = query.Where("cloud_disk_files.id = ?", in.Id)
	} else {
		query = query.Where("cloud_disk_files.identity = ?", in.Identity)
	}

	if err := query.First(&file).Error; err != nil {
		printer.Error("File not found: %v", err)
		return nil, errcode.ErrInvalidArgument
	}

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

	// 更新字段
	file.Name = in.Name
	file.OriginalName = in.OriginalName
	file.MimeType = in.MimeType
	file.StoragePath = in.StoragePath
	file.Hash = in.Hash

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

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