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

// 创建目录
func CreateDir(ctx context.Context, in *pb.CreateDirRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// valid code
	if strings.TrimSpace(in.Name) == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if strings.TrimSpace(in.CloudIdentity) == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	// 构建完整路径
	var fullPath string
	if in.ParentId > 0 {
		var parentDir models.CloudDiskDir
		if err := impl.DBService.Where("id = ? AND passport_id = ?", in.ParentId, auth.ID).First(&parentDir).Error; err != nil {
			printer.Error("Parent directory not found: %v", err)
			return nil, errcode.ErrInvalidArgument
		}
		fullPath = filepath.Join(parentDir.Path, in.Name)
	} else {
		fullPath = "/" + in.Name
	}

	// 检查目录是否已存在
	var existingDir models.CloudDiskDir
	if err := impl.DBService.Where("path = ? AND passport_id = ?", fullPath, auth.ID).First(&existingDir).Error; err == nil {
		return nil, errcode.ErrAlreadyExists
	}

	record := models.CloudDiskDir{
		Std_IICUDS: types.Std_IICUDS{
			Identity: utils.UUID(),
		},
		Std_Passport: types.Std_Passport{
			PassportID:       auth.ID,
			PassportIdentity: auth.Identity,
		},
		CloudBase: models.CloudBase{
			CloudID:       uint(in.CloudId),
			CloudIdentity: in.CloudIdentity,
		},
		Name: in.Name,
		Path: fullPath,
	}

	if in.ParentId > 0 {
		parentId := uint(in.ParentId)
		record.ParentID = &parentId
	}

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

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