package common

import (
    "net/http"

    "bindbox-game/internal/code"
    "bindbox-game/internal/pkg/core"
)

func (h *handler) UploadWangEditorImage() core.HandlerFunc {
    return func(ctx core.Context) {
        fh, err := ctx.FormFile("file")
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "缺少文件"))
            return
        }
        f, err := fh.Open()
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, code.UploadError, err.Error()))
            return
        }
        defer f.Close()

        ct := fh.Header.Get("Content-Type")
        if ct == "" {
            ct = "application/octet-stream"
        }

        url, err := h.svc.UploadImage(ctx.RequestContext(), fh.Filename, f, ct)
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, code.UploadError, err.Error()))
            return
        }

        resp := map[string]any{
            "errno": 0,
            "data": map[string]string{
                "url": url,
            },
        }
        ctx.Payload(resp)
    }
}

