package logic

import (
	"context"
	"errors"
	"time"

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

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

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

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

// 获取文件访问链接（处理私有文件的鉴权）
func (l *GetFileUrlLogic) GetFileUrl(in *pb.GetFileUrlReq) (*pb.GetFileUrlResp, error) {
	if in == nil || in.GetFileId() == "" {
		return nil, errors.New("file id is required")
	}

	_, err := l.svcCtx.S3.HeadObject(l.ctx, &s3.HeadObjectInput{
		Bucket: &l.svcCtx.Config.S3Conf.Bucket,
		Key:    &in.FileId,
	})
	if err != nil {
		var nf *s3types.NotFound
		if errors.As(err, &nf) {
			return nil, errors.New("file not found")
		}
		return nil, err
	}

	presignClient := s3.NewPresignClient(l.svcCtx.S3)
	presigned, err := presignClient.PresignGetObject(l.ctx, &s3.GetObjectInput{
		Bucket: &l.svcCtx.Config.S3Conf.Bucket,
		Key:    &in.FileId,
	}, s3.WithPresignExpires(15*time.Minute))
	if err != nil {
		return nil, err
	}

	return &pb.GetFileUrlResp{Url: presigned.URL}, nil
}
