package crd

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

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

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

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

// CachedCRDPath returns the path to a cached CRD definition file.
func CachedCRDPath(stateDir, service, crdName string) string {
	return filepath.Join(CacheDir(stateDir, service), "crds", crdName+".yaml")
}

// CachedCRPath returns the path to a cached CR instances file.
func CachedCRPath(stateDir, service, resource string) string {
	return filepath.Join(CacheDir(stateDir, service), "crs", resource+".yaml")
}

// 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))
}
