package api

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

	"codex-pool/internal/config"
)

// Result 统一 API 响应
type Result struct {
	Code    int         `json:"code"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

// JSON 发送 JSON 响应
func JSON(w http.ResponseWriter, code int, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(data)
}

// Success 发送成功响应
func Success(w http.ResponseWriter, data interface{}) {
	JSON(w, http.StatusOK, Result{Code: 0, Data: data})
}

// Error 发送错误响应
func Error(w http.ResponseWriter, httpCode int, message string) {
	JSON(w, httpCode, Result{Code: -1, Message: message})
}

// CORS 跨域中间件
func CORS(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		origin := "*"
		if config.Global != nil && config.Global.CorsOrigin != "" {
			origin = config.Global.CorsOrigin
		}

		w.Header().Set("Access-Control-Allow-Origin", origin)
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Api-Key")
		w.Header().Set("Access-Control-Max-Age", "86400")

		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next(w, r)
	}
}
