package infra

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

// ConfigFromFile loads configuration from a file into target.
// The target must be a non-nil pointer to a struct (same as json.Unmarshal).
//
// Supported formats:
//   - JSON (.json) — full support via encoding/json
//   - YAML (.yaml, .yml) — stub: returns "not implemented"
//
// The format is determined by the file extension (case-insensitive).
func ConfigFromFile(path string, target any) error {
	lower := strings.ToLower(path)

	switch {
	case strings.HasSuffix(lower, ".json"):
		return loadJSON(path, target)
	case strings.HasSuffix(lower, ".yaml"), strings.HasSuffix(lower, ".yml"):
		return fmt.Errorf("config_from_file: YAML support not implemented; use a JSON file or add gopkg.in/yaml.v3")
	default:
		return fmt.Errorf("config_from_file: unsupported file extension for %q (supported: .json, .yaml, .yml)", path)
	}
}

func loadJSON(path string, target any) error {
	data, err := os.ReadFile(path)
	if err != nil {
		return fmt.Errorf("config_from_file: read %q: %w", path, err)
	}
	if err := json.Unmarshal(data, target); err != nil {
		return fmt.Errorf("config_from_file: parse JSON %q: %w", path, err)
	}
	return nil
}
