package core

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

func TestTestFixtureLoad(t *testing.T) {
	// Crear fixture temporal para los tests
	dir := t.TempDir()

	// Fixture JSON valido
	jsonPath := filepath.Join(dir, "test.json")
	if err := os.WriteFile(jsonPath, []byte(`{"host":"localhost","port":5432}`), 0o644); err != nil {
		t.Fatalf("write json fixture: %v", err)
	}

	// Fixture JSON invalido
	badJSONPath := filepath.Join(dir, "bad.json")
	if err := os.WriteFile(badJSONPath, []byte(`{not valid json`), 0o644); err != nil {
		t.Fatalf("write bad json fixture: %v", err)
	}

	t.Run("carga fixture JSON correctamente", func(t *testing.T) {
		var dst struct {
			Host string `json:"host"`
			Port int    `json:"port"`
		}
		err := TestFixtureLoad(t, jsonPath, &dst)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if dst.Host != "localhost" {
			t.Errorf("got host %q, want \"localhost\"", dst.Host)
		}
		if dst.Port != 5432 {
			t.Errorf("got port %d, want 5432", dst.Port)
		}
	})

	t.Run("archivo inexistente retorna error", func(t *testing.T) {
		var dst map[string]any
		err := TestFixtureLoad(t, filepath.Join(dir, "nonexistent.json"), &dst)
		if err == nil {
			t.Error("expected error for nonexistent file, got nil")
		}
	})

	t.Run("extension no soportada retorna error", func(t *testing.T) {
		txtPath := filepath.Join(dir, "file.txt")
		if err := os.WriteFile(txtPath, []byte("hello"), 0o644); err != nil {
			t.Fatalf("write txt: %v", err)
		}
		var dst any
		err := TestFixtureLoad(t, txtPath, &dst)
		if err == nil {
			t.Error("expected error for unsupported extension, got nil")
		}
	})

	t.Run("JSON invalido retorna error de parsing", func(t *testing.T) {
		var dst map[string]any
		err := TestFixtureLoad(t, badJSONPath, &dst)
		if err == nil {
			t.Error("expected error for invalid JSON, got nil")
		}
	})
}
