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

	// validate request id,identity.
	if in.Id == 0 && in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	// logic code
	var dir models.CloudDiskDir
	query := impl.DBService.Where("passport_id = ?", auth.ID)

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

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

	// 检查是否有子目录
	var subdirCount int64
	if err := impl.DBService.Model(&models.CloudDiskDir{}).Where("parent_id = ?", dir.ID).Count(&subdirCount).Error; err != nil {
		printer.Error("Check subdirectories error: %v", err)
		return nil, errcode.ErrDB
	}
	if subdirCount > 0 {
		return nil, errcode.ErrInvalidArgument
	}

	// 检查是否有文件
	var fileCount int64
	if err := impl.DBService.Model(&models.CloudDiskFile{}).Where("directory_id = ?", dir.ID).Count(&fileCount).Error; err != nil {
		printer.Error("Check files error: %v", err)
		return nil, errcode.ErrDB
	}
	if fileCount > 0 {
		return nil, errcode.ErrInvalidArgument
	}

	// 删除目录
	if err := impl.DBService.Delete(&dir).Error; err != nil {
		printer.Error("Delete directory error: %v", err)
		return nil, errcode.ErrDB
	}

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