package testenv

import (
	"io"
	"os"
	"path/filepath"
	"runtime"
	"testing"
)

// SyntheticGeoIPDB copies the MaxMind reference Country test database
// into a fresh temp directory and returns the absolute path. The same
// fixture is used by pkg/geoip tests, so all integration tests resolve
// the same set of synthetic IPs against the same country mapping.
func SyntheticGeoIPDB(t *testing.T) string {
	t.Helper()
	src := geoipFixturePath(t)
	data, err := os.ReadFile(src)
	if err != nil {
		t.Fatalf("read mmdb fixture %s: %v", src, err)
	}
	dst := filepath.Join(t.TempDir(), "GeoIP2-Country-Test.mmdb")
	if err := os.WriteFile(dst, data, 0o644); err != nil {
		t.Fatalf("write mmdb fixture: %v", err)
	}
	return dst
}

func geoipFixturePath(t *testing.T) string {
	t.Helper()
	_, file, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatalf("runtime.Caller failed")
	}
	// integration/testenv/geoip.go → workspace/pkg/geoip/...
	root := filepath.Dir(filepath.Dir(filepath.Dir(file)))
	return filepath.Join(root, "pkg", "geoip", "test-data", "test-data", "GeoIP2-Country-Test.mmdb")
}

// CopyFile copies src into dst with mode 0644. Convenience helper for
// container bind-mount preparation.
func CopyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()
	if _, err := io.Copy(out, in); err != nil {
		return err
	}
	return out.Chmod(0o644)
}
