package mongo

import (
	"testing"

	"github.com/zeromicro/go-zero/core/conf"
)

func loadMongoYAML(t *testing.T, snippet string) Conf {
	t.Helper()
	var cfg struct {
		Mongo Conf
	}
	if err := conf.LoadFromYamlBytes([]byte(snippet), &cfg); err != nil {
		t.Fatal(err)
	}
	return cfg.Mongo
}

func TestLoadMongoConf_hostAndPort(t *testing.T) {
	t.Parallel()
	c := loadMongoYAML(t, `Mongo:
  Host: 127.0.0.1
  Port: 27017
  Database: gateway
`)
	uri, err := buildConnectionURI(c)
	if err != nil {
		t.Fatal(err)
	}
	if uri != "mongodb://127.0.0.1:27017" {
		t.Fatalf("uri = %q", uri)
	}
}

func TestLoadMongoConf_withCompressorsArray(t *testing.T) {
	t.Parallel()
	c := loadMongoYAML(t, `Mongo:
  Host: 127.0.0.1:27017
  Database: gateway
  Compressors:
    - zstd
    - snappy
`)
	if len(c.Compressors) != 2 {
		t.Fatalf("compressors = %v", c.Compressors)
	}
}

func TestLoadMongoConf_compressorsStringRejected(t *testing.T) {
	t.Parallel()
	var cfg struct {
		Mongo Conf
	}
	err := conf.LoadFromYamlBytes([]byte(`Mongo:
  Host: 127.0.0.1:27017
  Database: gateway
  Compressors: zstd
`), &cfg)
	if err == nil {
		t.Fatal("expected type mismatch for Compressors string")
	}
}
