package migrate

import (
	"os"
	"path/filepath"
	"time"
)

const (
	// dumpCacheTTL is how long a cached dump is considered fresh.
	dumpCacheTTL = 24 * time.Hour

	// dumpsDirName is the subdirectory for cached dumps.
	dumpsDirName = "db-dumps"
)

// CacheDir returns the path to the dump cache directory for a service.
func CacheDir(stateDir, service string) string {
	return filepath.Join(stateDir, dumpsDirName, service)
}

// CachedDumpPath returns the path to the cached schema dump file.
func CachedDumpPath(stateDir, service string) string {
	return filepath.Join(CacheDir(stateDir, service), "schema.sql")
}

// CachedSeedPath returns the path to the cached seed data dump file.
func CachedSeedPath(stateDir, service string) string {
	return filepath.Join(CacheDir(stateDir, service), "seed.sql")
}

// IsCacheFresh returns true if the cached dump exists and is less than dumpCacheTTL old.
func IsCacheFresh(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}
	return time.Since(info.ModTime()) < dumpCacheTTL
}

// WriteCacheFile writes data to a cache file, creating directories as needed.
func WriteCacheFile(path string, data []byte) error {
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return err
	}
	return os.WriteFile(path, data, 0o600)
}

// ReadCacheFile reads a cached dump file.
func ReadCacheFile(path string) ([]byte, error) {
	return os.ReadFile(path)
}

// ClearCache removes all cached dumps for a service.
func ClearCache(stateDir, service string) error {
	return os.RemoveAll(CacheDir(stateDir, service))
}
