package upload

import (
	"fmt"
	"net/http"
	"strings"

	"mini-chat/configs"
	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/idgen"
)

type uploadImageResponse struct {
	RealImageUrl    string `json:"real_image_url"`    // 真实图片地址
	PreviewImageUrl string `json:"preview_image_url"` // 可预览图片地址
}

// UploadImage 上传图片
// @Summary 上传图片
// @Description 上传图片
// @Tags 通用
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "选择文件"
// @Success 200 {object} uploadImageResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/upload/image [post]
func (h *handler) UploadImage() core.HandlerFunc {
	return func(ctx core.Context) {
		file, err := ctx.FormFile("file")
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.UploadError,
				fmt.Sprintf("%s: %s", code.Text(code.UploadError), err.Error()),
			))
			return
		}

		if file == nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.UploadError,
				fmt.Sprintf("%s: %s", code.Text(code.UploadError), "缺少 file 文件"),
			))
			return
		}

		// 校验文件后缀
		extension := ""
		if dot := strings.LastIndexByte(file.Filename, '.'); dot != -1 {
			extension = file.Filename[dot+1:]
		}

		allowedExtensions := map[string]bool{
			"jpg":  true,
			"jpeg": true,
			"png":  true,
			"gif":  true,
		}

		if !allowedExtensions[strings.ToLower(extension)] {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.UploadError,
				fmt.Sprintf("%s: %s", code.Text(code.UploadError), "文件后缀应为 .jpg、.jpeg、.png、.gif"),
			))
			return
		}

		// 保存文件
		imagePath := fmt.Sprintf("image/%s.%s", idgen.GenerateUniqueID(), strings.ToLower(extension))
		filePath := fmt.Sprintf("%s/%s", configs.GetResourcesFilePath(), imagePath)
		if err := ctx.SaveUploadedFile(file, filePath); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.UploadError,
				fmt.Sprintf("%s: %s", code.Text(code.UploadError), err.Error()),
			))
			return
		}

		res := new(uploadImageResponse)
		res.RealImageUrl = filePath
		res.PreviewImageUrl = fmt.Sprintf("resources/%s", imagePath)

		ctx.Payload(res)
	}
}
