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

package file

import (
	"context"
	"errors"
	"io"
	"net/http"
	"strconv"

	"juwan-backend/app/objectstory/api/internal/svc"
	"juwan-backend/app/objectstory/api/internal/types"
	"juwan-backend/app/objectstory/rpc/fileservice"
	"juwan-backend/common/utils/contextj"

	"github.com/zeromicro/go-zero/core/logx"
)

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

// 文件上传接口
func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *types.UploadReq, r *http.Request) (resp *types.UploadResp, err error) {
	if req == nil {
		return nil, errors.New("invalid request")
	}

	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		return nil, errors.New("file is required")
	}
	defer func() {
		err := file.Close()
		if err != nil {
			logx.Errorf("failed to close file: %v", err)
			return
		}
	}()

	fileData, err := io.ReadAll(file)
	if err != nil {
		return nil, errors.New("read file failed")
	}
	if len(fileData) == 0 {
		return nil, errors.New("empty file is not allowed")
	}

	userID, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, contextj.ERRILLEGALUSER
	}

	rpcResp, err := l.svcCtx.FileRpc.Upload(l.ctx, &fileservice.UploadFileMetadataReq{
		FileName: fileHeader.Filename,
		FileSize: fileHeader.Size,
		FileType: req.Type,
		UserId:   strconv.FormatInt(userID, 10),
		FileData: fileData,
	})
	if err != nil {
		return nil, err
	}
	if rpcResp.GetUrl() == "" {
		return nil, errors.New("upload failed")
	}

	return &types.UploadResp{Url: rpcResp.GetUrl()}, nil
}
