package handler

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

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

// TokenHandler Token处理器
type TokenHandler struct {
	tokenRepo *repository.TokenRepository
}

// NewTokenHandler 创建Token处理器实例
func NewTokenHandler(tokenRepo *repository.TokenRepository) *TokenHandler {
	return &TokenHandler{
		tokenRepo: tokenRepo,
	}
}

// TokenResponse Token响应结构
type TokenResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// TokenInput Token输入结构
type TokenInput struct {
	Username string `json:"username"`
	Token    string `json:"token"`
}

// BatchAddTokens 批量添加Token（JSON数组: [{"username":"","token":""},...]）
func (h *TokenHandler) BatchAddTokens(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}

	var inputs []TokenInput
	if err := json.NewDecoder(r.Body).Decode(&inputs); err != nil {
		log.Printf("BatchAddTokens - decode error: %v", err)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(TokenResponse{Code: 400, Message: "invalid request body"})
		return
	}

	log.Printf("BatchAddTokens - received %d tokens", len(inputs))

	if len(inputs) == 0 {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(TokenResponse{Code: 400, Message: "empty array"})
		return
	}

	// 逐条插入
	var failed []TokenInput
	for _, input := range inputs {
		if input.Username == "" || input.Token == "" {
			failed = append(failed, input)
			continue
		}

		_, err := h.tokenRepo.Insert(input.Username, input.Token, true)
		if err != nil {
			log.Printf("BatchAddTokens - insert error: %v", err)
			failed = append(failed, input)
		}
	}

	w.Header().Set("Content-Type", "application/json")
	if len(failed) > 0 {
		json.NewEncoder(w).Encode(TokenResponse{
			Code:    207,
			Message: "partial success",
			Data:    map[string]interface{}{"failed": failed},
		})
		return
	}

	json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success"})
}

// GetAllTokens 查询所有Token
func (h *TokenHandler) GetAllTokens(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}

	records, err := h.tokenRepo.GetAll()
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success", Data: records})
}

// DeleteToken 删除Token
func (h *TokenHandler) DeleteToken(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}

	// 解析 form-data 或 URL 参数
	r.ParseMultipartForm(32 << 20)
	r.ParseForm()

	idStr := r.PostForm.Get("id")
	if idStr == "" {
		// 尝试从URL获取
		idStr = r.URL.Query().Get("id")
	}

	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		http.Error(w, "invalid id", http.StatusBadRequest)
		return
	}

	err = h.tokenRepo.Delete(id)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success"})
}

// UpdateToken 修改Token
func (h *TokenHandler) UpdateToken(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}

	// 解析 form-data
	r.ParseMultipartForm(32 << 20)
	r.ParseForm()

	idStr := r.PostForm.Get("id")
	username := r.PostForm.Get("username")
	token := r.PostForm.Get("token")
	isEnableStr := r.PostForm.Get("is_enable")

	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		http.Error(w, "invalid id", http.StatusBadRequest)
		return
	}

	isEnable := true
	if isEnableStr == "0" || isEnableStr == "false" {
		isEnable = false
	}

	err = h.tokenRepo.Update(id, username, token, isEnable)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success"})
}

// GetEnabledTokens 获取所有启用的Token
func (h *TokenHandler) GetEnabledTokens(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}

	records, err := h.tokenRepo.GetEnabledTokens()
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(TokenResponse{Code: 500, Message: err.Error()})
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(TokenResponse{Code: 200, Message: "success", Data: records})
}
