// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package file

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"
	"sundynix-micro-go/app/file/api/internal/oss_core"
	"sundynix-micro-go/app/file/api/internal/svc"
	"sundynix-micro-go/app/file/api/internal/types"
	"sundynix-micro-go/app/file/rpc/fileservice"
)

type DeleteFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 删除文件
func NewDeleteFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteFileLogic {
	return &DeleteFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteFileLogic) DeleteFile(req *types.IdsReq) error {
	if len(req.Ids) == 0 {
		return nil
	}

	// 1. 查询文件记录获取OSS Key
	resp, err := l.svcCtx.FileRpc.GetFilesByIds(l.ctx, &fileservice.GetFilesByIdsReq{
		Ids: req.Ids,
	})
	if err != nil {
		return err
	}

	// 2. 从OSS物理删除
	factory := oss_core.NewOSSFactory(l.svcCtx.FileRpc)
	uploader, err := factory.GetActiveUploader(l.ctx)
	if err == nil && uploader != nil {
		for _, file := range resp.Files {
			if file.Key != "" {
				_ = uploader.DeleteFile(l.ctx, file.Key)
			}
		}
	}

	// 3. 从数据库删除
	_, err = l.svcCtx.FileRpc.DeleteFiles(l.ctx, &fileservice.DeleteFilesReq{
		Ids: req.Ids,
	})

	return err
}
