package db_updater

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

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

	etag, _ := readFile(filenameEtag)

	client := resty.New().
		SetTimeout(2 * time.Minute).
		SetRetryCount(2).
		SetRetryWaitTime(5 * time.Second)
	resp, err := client.R().
		SetHeader("If-None-Match", etag).
		Get(url)

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

	switch resp.StatusCode() {
	case http.StatusNotModified:
		log.Info().
			Str("url", url).
			Str("etag", etag).
			Int("status_code", resp.StatusCode()).
			Str("status", resp.Status()).
			Msg("No update needed")
		return false
	case http.StatusOK:
		_ = writeFileSByte(filename, resp.Body())
		_ = writeFileString(filenameEtag, resp.Header().Get("Etag"))

		return true
	default:
		return false
	}
}

func readFile(file string) (string, error) {
	data, err := os.ReadFile(file)
	if err != nil {
		if os.IsNotExist(err) {
			return "", nil
		}
		return "", err
	}
	return string(data), nil
}

func writeFileString(file, content string) error {
	return writeFileSByte(file, []byte(content))
}

func writeFileSByte(file string, content []byte) error {
	return os.WriteFile(file, content, 0644)
}
