package upload

import (
	"net/http"
	"os"

	"tyc-server/app/main/api/internal/logic/upload"
	"tyc-server/app/main/api/internal/svc"
	"tyc-server/app/main/api/internal/types"
	"tyc-server/common/result"
	"tyc-server/pkg/lzkit/validator"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func ServeUploadedFileHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.ServeUploadedFileReq
		if err := httpx.Parse(r, &req); err != nil {
			result.ParamErrorResult(r, w, err)
			return
		}
		if err := validator.Validate(req); err != nil {
			result.ParamValidateErrorResult(r, w, err)
			return
		}
		l := upload.NewServeUploadedFileLogic(r.Context(), svcCtx)
		resp, err := l.ServeUploadedFile(&req)
		if err != nil {
			result.HttpResult(r, w, nil, err)
			return
		}
		if resp != nil && resp.FilePath != "" {
			f, openErr := os.Open(resp.FilePath)
			if openErr != nil {
				result.HttpResult(r, w, nil, openErr)
				return
			}
			defer f.Close()
			w.Header().Set("Content-Type", resp.ContentType)
			w.WriteHeader(http.StatusOK)
			_, _ = f.WriteTo(w)
			return
		}
		httpx.OkJson(w, resp)
	}
}
