package handler

import (
	"bytes"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"strconv"

	"kfz-goods-pricing/internal/service"
)

// GoodsHandler 商品处理器
type GoodsHandler struct {
	goodsService *service.GoodsService
}

// NewGoodsHandler 创建商品处理器实例
func NewGoodsHandler(goodsService *service.GoodsService) *GoodsHandler {
	return &GoodsHandler{
		goodsService: goodsService,
	}
}

// QueryGoods 查询商品接口
func (h *GoodsHandler) QueryGoods(w http.ResponseWriter, r *http.Request) {
	// 只支持POST请求
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// 读取原始body用于调试
	bodyBytes, _ := io.ReadAll(r.Body)
	bodyStr := string(bodyBytes)
	log.Printf("收到原始请求 Body: [%s]", bodyStr)
	log.Printf("Content-Type: [%s]", r.Header.Get("Content-Type"))

	// 重新创建body供ParseForm使用
	r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))

	// 解析参数 - ParseMultipartForm 同时支持 form-data 和 x-www-form-urlencoded
	if err := r.ParseMultipartForm(32 << 20); err != nil {
		// 尝试纯表单解析
		if err := r.ParseForm(); err != nil {
			log.Printf("ParseForm 失败: %v", err)
			http.Error(w, "Invalid request form", http.StatusBadRequest)
			return
		}
	}

	// 调试日志
	log.Printf("解析结果 - isbn: [%s], book_name: [%s], author: [%s], publishing: [%s], out_id: [%s], quality: [%s], query_index: [%s], user_id: [%s], placeholder_down_price: [%s], min_shipping_fee: [%s], min_price: [%s] ",
		r.FormValue("isbn"), r.FormValue("book_name"), r.FormValue("author"), r.FormValue("publishing"),
		r.FormValue("out_id"), r.FormValue("quality"),
		r.FormValue("query_index"), r.FormValue("user_id"), r.FormValue("placeholder_down_price"), r.FormValue("min_shipping_fee"), r.FormValue("min_price"))

	var req service.QueryRequest
	req.ISBN = r.FormValue("isbn")
	req.BookName = r.FormValue("book_name")
	req.Author = r.FormValue("author")
	req.Publishing = r.FormValue("publishing")
	req.OutID = r.FormValue("out_id")
	req.Quality = r.FormValue("quality")
	req.QueryIndex, _ = strconv.Atoi(r.FormValue("query_index"))
	req.UserID = r.FormValue("user_id")
	req.PlaceholderDownPrice, _ = strconv.ParseFloat(r.FormValue("placeholder_down_price"), 64)
	req.MinShippingFee, _ = strconv.ParseFloat(r.FormValue("min_shipping_fee"), 64)
	req.MinPrice, _ = strconv.ParseFloat(r.FormValue("min_price"), 64)

	// 调用服务层
	resp := h.goodsService.QueryGoods(&req)

	// 返回响应
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resp)
}
