package db_updater

import (
	"github.com/go-resty/resty/v2"
	"github.com/rs/zerolog/log"
	"net/http"
	"os"
	"path"
	"thuanle.me/ip-info/configs"
)

func download(url string) bool {
	log.Info().Str("url", url).Msg("Downloading DB")
	filename := configs.GeoDbFolder + path.Base(url)

	client := resty.New()
	resp, err := client.R().
		SetOutput(filename).
		SetHeader("If-None-Match", readETag(filename)).
		Get(url)

	if err != nil {
		log.Err(err).
			Str("url", url).
			Msg("Failed to fetch DB")
		return false
	}

	if resp.StatusCode() == http.StatusOK {
		writeETag(filename, resp.Header().Get("Etag"))
	} else {
		//log.Printf("No update needed: %v", resp.Status())
		return false
	}

	log.Info().
		Str("filename", filename).
		Msg("Downloaded DB")
	return true
}

// readETag reads the ETag from the file
func readETag(baseFile string) string {
	data, err := os.ReadFile(baseFile + ".etag")
	if err != nil {
		return ""
	}
	return string(data)
}

// writeETag writes the ETag to the file
func writeETag(baseFile, etag string) {
	err := os.WriteFile(baseFile+".etag", []byte(etag), 0644)
	if err != nil {
		log.Err(err).Msg("Failed to write ETag")
	}
}
