package restic

import "testing"

func TestMergeRestCreds(t *testing.T) {
	cases := []struct {
		name, url, user, pass, want string
	}{
		{"rest with creds", "rest:http://h:8000/p/", "u", "p", "rest:http://u:p@h:8000/p/"},
		{"rest no user — no-op", "rest:http://h:8000/p/", "", "p", "rest:http://h:8000/p/"},
		{
			"rest creds already inline — no-op",
			"rest:http://existing:secret@h:8000/p/", "u", "p",
			"rest:http://existing:secret@h:8000/p/",
		},
		{"non-rest s3 — no-op", "s3:s3.amazonaws.com/bucket", "u", "p", "s3:s3.amazonaws.com/bucket"},
		{"unparseable — pass through", "rest:not a url", "u", "p", "rest:not a url"},
		{"https URL kept intact", "rest:https://h/p/", "u", "p", "rest:https://u:p@h/p/"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := mergeRestCreds(c.url, c.user, c.pass)
			if got != c.want {
				t.Fatalf("mergeRestCreds(%q,%q,***) = %q; want %q", c.url, c.user, got, c.want)
			}
		})
	}
}

func TestRedactURL(t *testing.T) {
	cases := []struct{ in, want string }{
		{"rest:http://u:p@h:8000/p/", "rest:http://u:***@h:8000/p/"},
		{"rest:http://h:8000/p/", "rest:http://h:8000/p/"},
		{"https://u:p@example/", "https://u:***@example/"},
		{"s3:s3.amazonaws.com/bucket", "s3:s3.amazonaws.com/bucket"},
	}
	for _, c := range cases {
		got := RedactURL(c.in)
		if got != c.want {
			t.Fatalf("RedactURL(%q) = %q; want %q", c.in, got, c.want)
		}
	}
}
