package infra

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

func TestConfigFromFile(t *testing.T) {
	t.Run("carga JSON valido en struct", func(t *testing.T) {
		type Cfg struct {
			Host string `json:"host"`
			Port int    `json:"port"`
		}
		content := `{"host":"testhost","port":5432}`
		dir := t.TempDir()
		p := filepath.Join(dir, "config.json")
		if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
			t.Fatal(err)
		}

		var c Cfg
		if err := ConfigFromFile(p, &c); err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if c.Host != "testhost" || c.Port != 5432 {
			t.Errorf("unexpected: %+v", c)
		}
	})

	t.Run("JSON invalido retorna error", func(t *testing.T) {
		dir := t.TempDir()
		p := filepath.Join(dir, "bad.json")
		os.WriteFile(p, []byte("{not valid json}"), 0o600)

		var target map[string]any
		err := ConfigFromFile(p, &target)
		if err == nil {
			t.Error("expected error for invalid JSON")
		}
	})

	t.Run("archivo inexistente retorna error", func(t *testing.T) {
		var target map[string]any
		err := ConfigFromFile("/nonexistent/config.json", &target)
		if err == nil {
			t.Error("expected error for missing file")
		}
	})

	t.Run("extension YAML retorna not implemented", func(t *testing.T) {
		var target map[string]any
		err := ConfigFromFile("config.yaml", &target)
		if err == nil {
			t.Error("expected not-implemented error for YAML")
		}
	})

	t.Run("extension desconocida retorna error", func(t *testing.T) {
		var target map[string]any
		err := ConfigFromFile("config.toml", &target)
		if err == nil {
			t.Error("expected error for unsupported extension")
		}
	})
}
