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

package file

import (
	"context"

	"io"
	"net/http"

	"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 DownloadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 下载文件
func NewDownloadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DownloadFileLogic {
	return &DownloadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DownloadFileLogic) DownloadFile(w http.ResponseWriter, req *types.FileIdReq) error {
	// 1. 获取文件记录
	resp, err := l.svcCtx.FileRpc.GetFileById(l.ctx, &fileservice.GetFileByIdReq{
		Id: req.Id,
	})
	if err != nil {
		return err
	}

	// 2. 获取具体底层client
	factory := oss_core.NewOSSFactory(l.svcCtx.FileRpc)
	uploader, err := factory.GetActiveUploader(l.ctx)
	if err != nil {
		return err
	}

	// 3. 读取流
	reader, err := uploader.DownloadFile(l.ctx, resp.File.Key)
	if err != nil {
		return err
	}
	defer reader.Close()

	// 4. 返回文件流
	w.Header().Set("Content-Disposition", "attachment; filename=\""+resp.File.Name+"\"")
	w.Header().Set("Content-Type", "application/octet-stream")
	_, err = io.Copy(w, reader)
	return err
}
