package fileserviceimp

import (
	"mime/multipart"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.uber.org/zap"
)

func (a *API) getFile(r *http.Request) http.HandlerFunc {
	fileName := mutil.GetObjRef(r)
	return a.fileManager.Get(r.Context(), fileName)
}

func (a *API) closeFile(file multipart.File) {
	if err := file.Close(); err != nil {
		a.logger.Warn("Failed to close file", zap.Error(err))
	}
}

func (a *API) uploadFile(r *http.Request, _ *model.Account, _ *sresponse.TokenData) http.HandlerFunc {
	fileName := mutil.GetObjRef(r)

	file, _, err := r.FormFile(a.subDir)
	if err != nil {
		a.logger.Warn("Failed to read form request", zap.Error(err), zap.String("field_name", a.subDir))
		return response.BadRequest(a.logger, a.Name(), a.subDir+"_broken", err.Error())
	}
	defer a.closeFile(file)

	url, err := a.fileManager.Save(r.Context(), file, fileName)
	if err != nil {
		a.logger.Warn("Failed to store file", zap.Error(err), zap.String(mutil.ObjRefName(), fileName), zap.String("field_name", a.subDir))
		return response.Internal(a.logger, a.Name(), err)
	}

	return sresponse.FileUploaded(a.logger, url)
}
