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

	// validate request
	if in.DirectoryId == 0 {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.Name) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.StoragePath) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.CloudIdentity) == "" {
		return nil, errcode.ErrInvalidArgument
	}

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

	// 检查文件是否已存在（基于文件名和目录）
	var existingFile models.CloudDiskFile
	if err := impl.DBService.Where("name = ? AND directory_id = ?", in.Name, in.DirectoryId).First(&existingFile).Error; err == nil {
		// 文件已存在，可以选择覆盖或返回错误
		return nil, errcode.ErrAlreadyExists
	}

	// 生成文件哈希（如果未提供）
	fileHash := in.Hash
	if fileHash == "" {
		fileHash = utils.UUID() // 使用UUID作为默认哈希
	}

	record := models.CloudDiskFile{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
		},
		CloudBase: models.CloudBase{
			CloudID:       uint(in.CloudId),
			CloudIdentity: in.CloudIdentity,
		},
		DirectoryID:  func() *uint { id := uint(in.DirectoryId); return &id }(),
		Name:         in.Name,
		OriginalName: in.OriginalName,
		Size:         in.Size,
		MimeType:     in.MimeType,
		StoragePath:  in.StoragePath,
		Hash:         fileHash,
	}

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

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