package utils

import (
	"encoding/json"
	"exhibitionCentre/logging"
	"fmt"
	"net/http"
)

type ErrorInfo struct {
	Error string `json:"error"`
}

type TokenInfo struct {
	Token string `json:"token"`
}

func SendResponse(writer http.ResponseWriter, statusCode int, data []byte) {
	if writer == nil {
		logging.Log.Error("SendResponse Error: http.ResponseWriter == nil.")
		return
	}
	// set response header info
	writer.Header().Set("Content-Type", "application/json")
	// set status code
	writer.WriteHeader(statusCode)
	// send response
	writer.Write(data)
}

func SendSMSRequest(phoneNumber, verificationCode string) bool {
	url := fmt.Sprintf("http://221.179.215.39:8144/mtsnport/transms?uid=261&pwd=56tyuk&mobile=%s&msg=%s&srcid=381&dtime&para=2", phoneNumber, verificationCode)
	resp, err := http.Get(url)
	if err != nil {
		logging.Log.Error("Failed to send SMS message to SMS server!", err.Error())
		return false
	}
	return resp.StatusCode == 200
}

func SerializeErrorData(data string) []byte {
	if len(data) == 0 {
		return []byte("{}")
	}
	info := ErrorInfo{Error: data}
	if bytes, err := json.Marshal(info); err == nil {
		return bytes
	}
	return []byte("{}")
}

func SerializeToken(token string) []byte {
	info := TokenInfo{Token: token}
	if bytes, err := json.Marshal(info); err == nil {
		return bytes
	}
	return nil
}

func Serialize(data any) []byte {
	if bytes, err := json.Marshal(data); err == nil {
		return bytes
	}
	return nil
}

func RemoteIp(req *http.Request) string {
	var remoteAddr string
	// // RemoteAddr
	// remoteAddr = req.RemoteAddr
	// if remoteAddr != "" {
	// 	return remoteAddr
	// }
	// // ipv4
	// remoteAddr = req.Header.Get("ipv4")
	// if remoteAddr != "" {
	// 	return remoteAddr
	// }
	// //
	// remoteAddr = req.Header.Get("XForwardedFor")
	// if remoteAddr != "" {
	// 	return remoteAddr
	// }
	// // X-Forwarded-For
	// remoteAddr = req.Header.Get("X-Forwarded-For")
	// if remoteAddr != "" {
	// 	return remoteAddr
	// }
	// X-Real-Ip
	remoteAddr = req.Header.Get("X-Real-Ip")
	if remoteAddr != "" {
		return remoteAddr
	} else {
		remoteAddr = "127.0.0.1"
	}
	return remoteAddr
}
