package store

import (
	"testing"
	"time"

	"github.com/go-sql-driver/mysql"

	"github.com/wangjia/pangolin/server/internal/config"
)

// TestBuildDSN_ConflictingParamsOverridden verifies that a DSN that already
// contains conflicting timezone / locale settings is corrected by buildDSN:
// ParseTime, Loc, Collation and the time_zone param are all forced to UTC.
func TestBuildDSN_ConflictingParamsOverridden(t *testing.T) {
	// A DSN with parseTime=false, the wrong timezone, and a local location.
	cfg := &config.Config{
		DSN: "root:pass@tcp(localhost:3306)/db?parseTime=false&time_zone=%27Asia%2FShanghai%27",
	}

	dsn, err := buildDSN(cfg)
	if err != nil {
		t.Fatalf("buildDSN: %v", err)
	}

	parsed, err := mysql.ParseDSN(dsn)
	if err != nil {
		t.Fatalf("ParseDSN on output: %v", err)
	}

	if !parsed.ParseTime {
		t.Error("ParseTime should be overridden to true")
	}
	if parsed.Loc != time.UTC {
		t.Errorf("Loc = %v, want time.UTC (override of Local)", parsed.Loc)
	}
	if got := parsed.Params["time_zone"]; got != "'+00:00'" {
		t.Errorf("time_zone param = %q, want \"'+00:00'\" (override)", got)
	}
	if parsed.Collation != "utf8mb4_unicode_ci" {
		t.Errorf("Collation = %q, want utf8mb4_unicode_ci", parsed.Collation)
	}
}
