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 DeleteFile(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 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 err := impl.DBService.Delete(&file).Error; err != nil {
		printer.Error("Delete file error: %v", err)
		return nil, errcode.ErrDB
	}

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