package file

import (
	"mime/multipart"

	"github.com/gin-gonic/gin"
	"github.com/perfect-panel/server/internal/logic/public/file"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/result"
)

// Upload file to RustFS
func FileUploadHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
	return func(c *gin.Context) {
		var req types.FileUploadRequest
		_ = c.ShouldBind(&req)
		validateErr := svcCtx.Validate(&req)
		if validateErr != nil {
			result.ParamErrorResult(c, validateErr)
			return
		}

		fileHeader, err := c.FormFile("file")
		if err != nil {
			result.ParamErrorResult(c, err)
			return
		}

		fileReader, err := fileHeader.Open()
		if err != nil {
			result.HttpResult(c, nil, err)
			return
		}
		defer func(file multipart.File) {
			_ = file.Close()
		}(fileReader)

		l := file.NewFileUploadLogic(c.Request.Context(), svcCtx)
		resp, err := l.FileUpload(&req, fileHeader, fileReader)
		result.HttpResult(c, resp, err)
	}
}
