package api

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/prism/proxy/internal/geodata"
)

func (s *Server) geoStatus(c *gin.Context) {
	ctx := c.Request.Context()
	settings, err := s.app.Store.GetSettings(ctx)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	cfg := geodata.ConfigFromSettings(settings)
	c.JSON(http.StatusOK, gin.H{
		"ready":          geodata.Ready(s.app.DataDir),
		"auto_download":  settings["geo_auto_download"] != "false",
		"files":          geodata.Status(s.app.DataDir, cfg),
		"default_urls":   geodata.DefaultConfig(),
	})
}

type geoUpdateReq struct {
	Force bool `json:"force"`
}

func (s *Server) geoUpdate(c *gin.Context) {
	var req geoUpdateReq
	_ = c.ShouldBindJSON(&req)

	ctx := c.Request.Context()
	settings, err := s.app.Store.GetSettings(ctx)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	cfg := geodata.ConfigFromSettings(settings)
	geodata.ApplyMihomoURLs(cfg)

	updated, err := geodata.Ensure(s.app.DataDir, cfg, req.Force)
	if err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	_ = s.app.Store.AddAuditLog(ctx, "update", "geo", "updated: "+joinNames(updated))
	s.logs.Add("info", "prism", "geo data updated")
	_ = s.app.ReloadEngine(ctx)

	c.JSON(http.StatusOK, gin.H{
		"ok":      true,
		"updated": updated,
		"ready":   geodata.Ready(s.app.DataDir),
		"files":   geodata.Status(s.app.DataDir, cfg),
	})
}

func joinNames(names []string) string {
	if len(names) == 0 {
		return "none (already present)"
	}
	out := names[0]
	for i := 1; i < len(names); i++ {
		out += ", " + names[i]
	}
	return out
}

func geoDataReady(dataDir string) bool {
	return geodata.Ready(dataDir)
}

func applyGeoSettings(dataDir string, settings map[string]string) {
	geodata.InitHomeDir(dataDir)
	geodata.ApplyMihomoURLs(geodata.ConfigFromSettings(settings))
}