package logic

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"path/filepath"
	"strings"

	"juwan-backend/app/objectstory/rpc/internal/svc"
	"juwan-backend/app/objectstory/rpc/pb"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
)

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

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 简单上传（适合小文件，或保存元数据）
func (l *UploadLogic) Upload(in *pb.UploadFileMetadataReq) (*pb.UploadFileResp, error) {
	if in == nil {
		return nil, errors.New("invalid request")
	}
	if len(in.GetFileData()) == 0 {
		return nil, errors.New("file data is required")
	}
	if in.GetFileName() == "" {
		return nil, errors.New("file name is required")
	}
	if in.GetFileType() == "" {
		return nil, errors.New("file type is required")
	}

	fileID := uuid.NewString()
	ext := strings.ToLower(filepath.Ext(in.GetFileName()))
	if len(ext) > 10 {
		ext = ""
	}
	objectKey := fmt.Sprintf("%s/%s/%s%s", in.GetFileType(), in.GetUserId(), fileID, ext)

	_, err := l.svcCtx.S3.PutObject(l.ctx, &s3.PutObjectInput{
		Bucket:        &l.svcCtx.Config.S3Conf.Bucket,
		Key:           &objectKey,
		Body:          bytes.NewReader(in.GetFileData()),
		ContentLength: aws.Int64(int64(len(in.GetFileData()))),
	})
	if err != nil {
		return nil, err
	}

	url := strings.TrimRight(l.svcCtx.Config.S3Conf.Endpoint, "/") + "/" + l.svcCtx.Config.S3Conf.Bucket + "/" + objectKey

	return &pb.UploadFileResp{
		Url:    url,
		FileId: objectKey,
	}, nil
}
