package contact

import (
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"

	"wechat-api/internal/logic/contact"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
)

const (
	defaultMultipartMemory = 32 << 20 // 32 MB
)

// swagger:route post /contact/importWhatsappContact contact ImportWhatsappContact
//
// 导入Whatsapp联系人
//
// 导入Whatsapp联系人
//
// Parameters:
//  + name: body
//    require: true
//    in: body
//    type: ImportWhatsappContactReq
//
// Responses:
//  200: BaseDataInfo

func ImportWhatsappContactHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseMultipartForm(defaultMultipartMemory); err != nil {
			httpx.Error(w, err)
			return
		}

		file, header, err := r.FormFile("file")

		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		if file == nil {
			httpx.ErrorCtx(r.Context(), w, errors.New("upload file cannot be null"))
			return
		}

		fmt.Printf("header=%+v size=%d filename=%v\n", header.Header, header.Size, header.Filename)

		var req types.ImportWhatsappContactReq
		if err := httpx.Parse(r, &req, true); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := contact.NewImportWhatsappContactLogic(r.Context(), svcCtx)
		resp, err := l.ImportWhatsappContact(&req, file)

		// 删除临时文件
		_ = r.MultipartForm.RemoveAll()
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
