package routes

import (
	"git.trj.tw/golang/go-geoip/module/geoip"
	"github.com/gin-gonic/contrib/cors"
	"github.com/gin-gonic/gin"
)

// NewEngine -
func NewEngine() *gin.Engine {
	r := gin.Default()

	r.Use(cors.Default())
	return r
}

// RegRoutes -
func RegRoutes(r *gin.Engine) {
	r.GET("/", func(c *gin.Context) {
		c.String(200, "success")
	})

	r.GET("/geo", func(c *gin.Context) {
		ip := c.DefaultQuery("ip", "")
		if len(ip) == 0 {
			c.AbortWithStatusJSON(400, map[string]interface{}{
				"message": "no ip input",
			})
			return
		}

		geo, err := geoip.QueryGEO(ip)
		if err != nil {
			c.AbortWithStatusJSON(500, map[string]interface{}{
				"message": err.Error(),
			})
			return
		}
		if geo == nil {
			c.AbortWithStatusJSON(500, map[string]interface{}{
				"message": "geo not found",
			})
			return
		}

		c.JSON(200, geo)
	})
}
