package device

import (
	"errors"
	"net"

	"github.com/oschwald/maxminddb-golang"
)

var (
	errGeoNotFound = errors.New("no record found")

	defaultGeoIPPaths = []string{
		"/var/lib/GeoIP/GeoLite2-Country.mmdb",
	}
)

type geoIPDb struct {
	readers []*maxminddb.Reader
}

func newGeoIP(paths []string) (*geoIPDb, error) {
	if len(paths) == 0 {
		paths = defaultGeoIPPaths
	}

	db := new(geoIPDb)
	for _, path := range paths {
		geodb, err := maxminddb.Open(path)
		if err != nil {
			return nil, err
		}
		db.readers = append(db.readers, geodb)
	}
	return db, nil
}

func (db *geoIPDb) getZoneForIP(ip net.IP) (string, error) {
	// Only look up a single attribute (country).
	var record struct {
		Country struct {
			ISOCode string `maxminddb:"iso_code"`
		} `maxminddb:"country"`
	}

	for _, r := range db.readers {
		if err := r.Lookup(ip, &record); err == nil {
			return record.Country.ISOCode, nil
		}
	}
	return "", errGeoNotFound
}