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

package file

import (
	"context"
	"errors"
	"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"
	"google.golang.org/grpc/status"
)

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

// 文件获取接口 (如果是私有文件，通过此接口获取或重定向)
func NewGetFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFileLogic {
	return &GetFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetFileLogic) GetFile(req *types.GetFileReq) (string, error) {
	if req == nil || req.FileId == "" {
		return "", errors.New("file id is required")
	}

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

	rpcResp, err := l.svcCtx.FileRpc.GetFileUrl(l.ctx, &fileservice.GetFileUrlReq{
		FileId: req.FileId,
		UserId: strconv.FormatInt(userID, 10),
	})
	if err != nil {
		return "", errors.New(status.Convert(err).Message())
	}
	if rpcResp.GetUrl() == "" {
		return "", errors.New("file url is empty")
	}

	return rpcResp.GetUrl(), nil
}
