package domain

import (
	"testing"
)

func TestGetTargetURL(t *testing.T) {
	// Empty repos should not find any short.
	RegisterRepositories(make(MockShortRepo), nil)
	_, err := GetTargetURL("")
	if err == nil {
		t.Error("empty repository should fail to get a target")
	}

	var mockSR MockShortRepo = make(map[ShortURL]TargetURL)
	shortURL := "some_short"
	expected := TargetURL{URL: URL("some target")}
	mockSR[ShortURL{URL: URL(shortURL)}] = expected
	RegisterRepositories(mockSR, nil)

	// Existing shorts should return proper target.
	actual, err := GetTargetURL(shortURL)
	if err != nil {
		t.Error("short with an existing target should be found")
	}
	if actual != string(expected.URL) {
		t.Error("short with an existing target should return it")
	}

	// Non-existent shorts should fail.
	_, err = GetTargetURL(shortURL + "_other")
	if err == nil {
		t.Error("short with no existing target should not be found")
	}
}

func TestGetShortURL(t *testing.T) {
	// No repo should be able to return a short for an empty target.
	RegisterRepositories(nil, nil)
	_, _, err := GetShortURL("")
	if err == nil {
		t.Error("empty repository should fail to get a short for an empty URL")
	}

	// Empty repos unable to create shorts should not find any short.
	RegisterRepositories(nil, MakeMockTargetRepo(false))
	_, isNew, err := GetShortURL("some_target")
	if err == nil {
		t.Error("empty repository should fail to get a short")
	}
	if isNew {
		t.Error("empty repository without create ability should fail to create a short")
	}

	// Empty repos able to create shorts should return a short for a valid target.
	RegisterRepositories(nil, MakeMockTargetRepo(true))
	const targetURL = "some_target"
	actual, isNew, err := GetShortURL(targetURL)
	if err != nil {
		t.Error("repository with create ability should not fail to create a short")
	}
	if !isNew {
		t.Error("repository creating a new short should report is as new")
	}
	if len(actual) == 0 {
		t.Error("repository should not return empty short URLs")
	}
	// Specific to mock.
	if actual != targetURL {
		t.Error("mock repository should return correct generated short")
	}

	// Repos with a matching short for a target should return it as non-new.
	actual, isNew, err = GetShortURL(targetURL)
	if err != nil {
		t.Error("repository with matching short should return it")
	}
	if isNew {
		t.Error("repository with matching short should now claim it is new")
	}
	// Specific to mock.
	if actual != targetURL {
		t.Error("mock repository should return correct generated short")
	}
}