package listings

import (
	"context"
	"math"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"sync"
	"testing"
)

// testRecords are test data only: import lines shaped like the legacy DB
// export (41625316 and 37082064 copied from the live localpages records),
// plus made-up records for the cases normalisation must handle.
const testRecords = `{"id":"41625316","title":"Ashburn Children's Dentistry - Dr. Lynda Dean-Duru","zip":"20147","address":"44025 Pipeline Plaza ","state":"VA","city":"Ashburn","phones":["(703) 723-8440 (Main)"],"lat":"39.021595","lon":"-77.478088","special_offer":"Call one of \"America's Top Dentists\" Now!","special_offer_url":"http:\/\/gtscii.yext-wraps.com\/plclick?pid=EAzeX9WdJk&ids=1528238","category":"Pediatric Dentistry, Dentists, Cosmetic Dentists, Orthodontists","website":"http:\/\/ashburnpediatricdental.com","description":"At Ashburn Children's Dentistry we provide a full range of services.","business_hour":"","payment_options":"American Express, Cash, Check, ","email":"office@example.com","business_name":"Ashburn Children's Dentistry - Dr. Lynda Dean-Duru","image":["http:\/\/a.mktgcdn.com\/p\/abc\/233x350","http:\/\/other.example.com\/x.jpg"],"attribution":null,"change_code":"A","suppression_id":"","yext_id":"1528238"}
{"id":"37082064","title":"Apt Kolman P DMD","zip":"20147","address":"44095  Pipeline Plz","state":"VA","city":"Ashburn","phones":[],"lat":"39.022598","lon":"-77.475403","category":"","website":"","business_name":"Apt Kolman P DMD","image":[],"change_code":"","suppression_id":"","yext_id":""}
{"id":100,"business_name":"Zeta Dental & Ortho","address":"1 Main St","city":"ashburn","state":"va","zip":"20148","lat":39.1,"lon":-77.5,"phones":[{"number":"703.555.0100","label":"Office"},"1:7035550101:Fax","555-0102"],"website":"website~~https://zeta.example.com||https://zeta.example.com","category":"Dentists,","record_id":"localeze-9"}
{"id":"101","business_name":"Alpha Plumbing","address":"","city":"Los Angeles","state":"CA","zip":"90001","lat":"","lon":"","phones":["(213) 555-0100"],"website":"www.alpha.example.com","category":"Plumbers","record_id":"ll-1"}
{"id":"102","business_name":"Hidden Business","city":"Ashburn","state":"VA","suppression_id":"77"}
{"id":"103","business_name":"Deleted Business","city":"Ashburn","state":"VA","change_code":"D"}
{"id":"abc","business_name":"Bad Id","city":"Ashburn","state":"VA"}
{"id":"104","business_name":"No State","city":"Ashburn","state":"ZZ"}
not json

{"id":"100","business_name":"Duplicate Of 100","city":"Ashburn","state":"VA"}
`

func testStore(t *testing.T) *JSONLStore {
	t.Helper()
	store, err := ReadJSONL(strings.NewReader(testRecords))
	if err != nil {
		t.Fatal(err)
	}
	return store
}

func TestReadJSONL_Normalises(t *testing.T) {
	store := testStore(t)
	if len(store.byID) != 4 {
		t.Fatalf("loaded %d listings, want 4 (suppressed, deleted, invalid and duplicate records skipped)", len(store.byID))
	}
	for _, id := range []string{"102", "103", "104"} {
		if _, ok, _ := store.Get(context.Background(), id); ok {
			t.Errorf("listing %s should be skipped", id)
		}
	}

	l, ok, err := store.Get(context.Background(), "41625316")
	if !ok || err != nil {
		t.Fatalf("Get(41625316) = %v, %v", ok, err)
	}
	lat, lon := 39.021595, -77.478088
	want := Listing{
		ID:             "41625316",
		Name:           "Ashburn Children's Dentistry - Dr. Lynda Dean-Duru",
		URL:            "/va/ashburn/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru",
		Address:        "44025 Pipeline Plaza",
		City:           "Ashburn",
		State:          "VA",
		Zip:            "20147",
		Lat:            &lat,
		Lon:            &lon,
		Phones:         []Phone{{Number: "(703) 723-8440", Tel: "+17037238440", Label: "Main"}},
		Website:        "http://ashburnpediatricdental.com",
		Categories:     []string{"Pediatric Dentistry", "Dentists", "Cosmetic Dentists", "Orthodontists"},
		Description:    "At Ashburn Children's Dentistry we provide a full range of services.",
		Hours:          []string{},
		PaymentOptions: []string{"American Express", "Cash", "Check"},
		SpecialOffer:   &SpecialOffer{Text: `Call one of "America's Top Dentists" Now!`, URL: "http://gtscii.yext-wraps.com/plclick?pid=EAzeX9WdJk&ids=1528238"},
		Images:         []string{"https://a.mktgcdn.com/p/abc/233x350", "http://other.example.com/x.jpg"},
		Videos:         []string{},
		YextID:         "1528238",
		Source:         "yext",
	}
	if !reflect.DeepEqual(l, want) {
		t.Errorf("normalised listing:\n got %+v\nwant %+v", l, want)
	}

	bare, _, _ := store.Get(context.Background(), "37082064")
	if bare.Address != "44095 Pipeline Plz" || bare.Source != "" || bare.SpecialOffer != nil ||
		bare.Phones == nil || bare.Categories == nil || bare.Images == nil || bare.PaymentOptions == nil ||
		bare.Hours == nil || bare.Videos == nil || bare.YextID != "" {
		t.Errorf("bare listing: %+v (want collapsed spaces, empty lists, no offer)", bare)
	}

	zeta, _, _ := store.Get(context.Background(), "100")
	wantPhones := []Phone{
		{Number: "(703) 555-0100", Tel: "+17035550100", Label: "Office"},
		{Number: "(703) 555-0101", Tel: "+17035550101", Label: "Fax"},
	}
	if !reflect.DeepEqual(zeta.Phones, wantPhones) {
		t.Errorf("phones = %+v, want %+v (7-digit number dropped)", zeta.Phones, wantPhones)
	}
	if zeta.Name != "Zeta Dental & Ortho" || zeta.Website != "https://zeta.example.com" || zeta.City != "ashburn" || zeta.State != "VA" ||
		zeta.Source != "localeze" || !reflect.DeepEqual(zeta.Categories, []string{"Dentists"}) || zeta.URL != "/va/ashburn/100-zeta-dental-and-ortho" {
		t.Errorf("first record of id 100: %+v", zeta)
	}

	alpha, _, _ := store.Get(context.Background(), "101")
	if alpha.Website != "https://www.alpha.example.com" || alpha.Lat != nil || alpha.Lon != nil || alpha.Source != "ll" ||
		alpha.URL != "/ca/los-angeles/101-alpha-plumbing" {
		t.Errorf("alpha: %+v", alpha)
	}
}

func TestWebsite(t *testing.T) {
	for in, want := range map[string]string{
		"website~~https://x.example.com||https://x.example.com": "https://x.example.com",
		"www.x.example.com":       "https://www.x.example.com",
		"http://x.example.com/a":  "http://x.example.com/a",
		"javascript:alert(1)":     "",
		"":                        "",
		"website~~||https://y.io": "https://y.io",
	} {
		if got := website(in); got != want {
			t.Errorf("website(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestSearch(t *testing.T) {
	store := testStore(t)
	ashburn := Location{City: "Ashburn", State: "VA"}
	ids := func(r Result) []string {
		out := []string{}
		for _, l := range r.Listings {
			out = append(out, l.ID)
		}
		return out
	}
	for _, tt := range []struct {
		name  string
		q     Query
		ids   []string
		total int
		city  string
	}{
		{"every business in the city, Yext first then A to Z", Query{Location: ashburn}, []string{"41625316", "37082064", "100"}, 3, "Ashburn"},
		{"keyword matches categories", Query{Keyword: "dentists", Location: ashburn}, []string{"41625316", "100"}, 2, "Ashburn"},
		{"keyword matches the name, any case", Query{Keyword: "KOLMAN", Location: ashburn}, []string{"37082064"}, 1, "Ashburn"},
		{"every word must match", Query{Keyword: "pediatric dentistry", Location: ashburn}, []string{"41625316"}, 1, "Ashburn"},
		{"a word that matches nothing", Query{Keyword: "dentists plumbing", Location: ashburn}, []string{}, 0, "Ashburn"},
		{"& matches and", Query{Keyword: "dental and ortho", Location: ashburn}, []string{"100"}, 1, "Ashburn"},
		{"city with a hyphen, state in lowercase", Query{Location: Location{City: "los-angeles", State: "ca"}}, []string{"101"}, 1, "Los Angeles"},
		{"page 2", Query{Location: ashburn, PageSize: 2, Page: 2}, []string{"100"}, 3, "Ashburn"},
		{"past the last page", Query{Location: ashburn, PageSize: 2, Page: 3}, []string{}, 3, "Ashburn"},
		{"the largest page", Query{Location: ashburn, PageSize: 2, Page: math.MaxInt}, []string{}, 3, "Ashburn"},
		{"a page whose offset overflows", Query{Location: ashburn, PageSize: MaxPageSize, Page: math.MaxInt/MaxPageSize + 1}, []string{}, 3, "Ashburn"},
		{"unknown city", Query{Location: Location{City: "Nowhere", State: "VA"}}, []string{}, 0, ""},
		{"no location", Query{Keyword: "dentists"}, []string{}, 0, ""},
	} {
		t.Run(tt.name, func(t *testing.T) {
			r, err := store.Search(context.Background(), tt.q)
			if err != nil {
				t.Fatal(err)
			}
			if got := ids(r); !reflect.DeepEqual(got, tt.ids) || r.Total != tt.total || r.CityName != tt.city {
				t.Errorf("got %v total %d city %q, want %v total %d city %q", got, r.Total, r.CityName, tt.ids, tt.total, tt.city)
			}
		})
	}

	r, _ := store.Search(context.Background(), Query{Location: ashburn, PageSize: 2})
	if r.Page != 1 || r.PageSize != 2 || r.TotalPages != 2 {
		t.Errorf("paging: page %d size %d pages %d, want 1, 2, 2", r.Page, r.PageSize, r.TotalPages)
	}
	if r, _ := store.Search(context.Background(), Query{Location: ashburn, PageSize: 500}); r.PageSize != MaxPageSize {
		t.Errorf("page size = %d, want the cap %d", r.PageSize, MaxPageSize)
	}
}

func TestNearby(t *testing.T) {
	store := testStore(t)
	l, _, _ := store.Get(context.Background(), "41625316")
	got, err := store.Nearby(context.Background(), l, "", 5)
	if err != nil || len(got) != 1 || got[0].ID != "100" {
		t.Errorf("Nearby by category = %+v, %v; want only 100 (shares Dentists, excludes itself)", got, err)
	}
	got, _ = store.Nearby(context.Background(), l, "kolman", 5)
	if len(got) != 2 {
		t.Errorf("Nearby with a keyword = %d listings, want 2", len(got))
	}
	if got, _ = store.Nearby(context.Background(), l, "kolman", 1); len(got) != 1 {
		t.Errorf("Nearby n=1 = %d listings", len(got))
	}
}

func TestDisabled(t *testing.T) {
	var store Store = Disabled{}
	if store.Available() {
		t.Error("Disabled is available")
	}
	if _, err := store.Search(context.Background(), Query{}); err != ErrUnavailable {
		t.Errorf("Search err = %v", err)
	}
	if ok, err := store.Exists(context.Background(), Query{}); ok || err != ErrUnavailable {
		t.Errorf("Exists = %v, %v", ok, err)
	}
	if _, _, err := store.Get(context.Background(), "1"); err != ErrUnavailable {
		t.Errorf("Get err = %v", err)
	}
	if _, err := store.Nearby(context.Background(), Listing{}, "", 1); err != ErrUnavailable {
		t.Errorf("Nearby err = %v", err)
	}
	if _, err := store.Cities(context.Background(), "VA"); err != ErrUnavailable {
		t.Errorf("Cities err = %v", err)
	}
	if _, err := store.States(context.Background()); err != ErrUnavailable {
		t.Errorf("States err = %v", err)
	}
	if _, ok, err := store.ResolveLocation(context.Background(), "Ashburn, VA"); ok || err != ErrUnavailable {
		t.Errorf("ResolveLocation = %v, %v", ok, err)
	}
}

func TestNewStore(t *testing.T) {
	if _, ok := NewStore("").(Disabled); !ok {
		t.Error("no path: want Disabled")
	}
	if _, ok := NewStore(filepath.Join(t.TempDir(), "missing.jsonl")).(Disabled); !ok {
		t.Error("missing file: want Disabled")
	}
	path := filepath.Join(t.TempDir(), "listings.jsonl")
	if err := os.WriteFile(path, []byte(testRecords), 0o644); err != nil {
		t.Fatal(err)
	}
	store := NewStore(path)
	if !store.Available() {
		t.Fatal("loaded file: want an available store")
	}
	if _, ok, _ := store.Get(context.Background(), "37082064"); !ok {
		t.Error("loaded store is missing 37082064")
	}
}

func TestSlugs(t *testing.T) {
	for in, want := range map[string]string{
		"Los Angeles":   "los-angeles",
		"los+angeles":   "los-angeles",
		" St. Louis ":   "st-louis",
		"Coeur d'Alene": "coeur-d-alene",
		"NEW-YORK":      "new-york",
	} {
		if got := CitySlug(in); got != want {
			t.Errorf("CitySlug(%q) = %q, want %q", in, got, want)
		}
	}
	for in, want := range map[string]string{
		"Ashburn Children's Dentistry - Dr. Lynda Dean-Duru": "ashburn-childrens-dentistry-dr-lynda-dean-duru",
		"Miller & Smith":   "miller-and-smith",
		"My Kid’s Dentist": "my-kids-dentist",
		"Austin's":         "austins",
		"!!!":              "",
	} {
		if got := NameSlug(in); got != want {
			t.Errorf("NameSlug(%q) = %q, want %q", in, got, want)
		}
	}
	if got := ListingURL("VA", "Ashburn", "37082064", "Apt Kolman P DMD"); got != "/va/ashburn/37082064-apt-kolman-p-dmd" {
		t.Errorf("ListingURL = %q", got)
	}
	if got := ListingURL("CA", "Los Angeles", "5", "!!!"); got != "/ca/los-angeles/5" {
		t.Errorf("ListingURL without a name slug = %q", got)
	}
}

func TestParseLocation(t *testing.T) {
	for _, tt := range []struct {
		in   string
		want Location
		ok   bool
	}{
		{"Ashburn, VA", Location{"Ashburn", "VA"}, true},
		{"los angeles,ca", Location{"los angeles", "CA"}, true},
		{"  New   York ,  ny ", Location{"New York", "NY"}, true},
		{"Austin TX", Location{"Austin", "TX"}, true},
		{"Washington, dc", Location{"Washington", "DC"}, true},
		{"Delhi, DL", Location{}, false},
		{"Chicago", Location{}, false},
		{", VA", Location{}, false},
		{"", Location{}, false},
	} {
		got, ok := ParseLocation(tt.in)
		if got != tt.want || ok != tt.ok {
			t.Errorf("ParseLocation(%q) = %+v, %v; want %+v, %v", tt.in, got, ok, tt.want, tt.ok)
		}
	}
	l := Location{City: "Los Angeles", State: "CA"}
	if l.Label() != "Los Angeles, CA" || l.Path() != "/ca/los-angeles" {
		t.Errorf("Label %q Path %q", l.Label(), l.Path())
	}
	if !IsStateCode("VA") || !IsStateCode("dc") || IsStateCode("zz") || IsStateCode("") {
		t.Error("IsStateCode")
	}
}

// detailRecords are import lines of live localpages records (fields copied
// from their detail pages' searchDetails, email left out; 16668312's
// description cut short), plus made-up records for the "::" payment split, a
// "1:number:label" phone, HTML in the description, video URL forms and a
// group.
const detailRecords = `{"id": "41727058", "business_name": "Cupid Pets", "address": "43150 Broadlands Center Plaza Suite 152 Box 165 ", "city": "Ashburn", "state": "VA", "zip": "20148", "lat": "39.026993", "lon": "-77.508575", "phones": ["(571) 271-6500 (Main)", "(703) 723-4000 (Alt)"], "category": "Pet & Animal Sitting, Exercising & Day Care Services", "business_hour": "Monday : 8:00 AM - 5:00 PM<br>Tuesday : 8:00 AM - 5:00 PM<br>Wednesday : 8:00 AM - 5:00 PM<br>Thursday : 8:00 AM - 5:00 PM<br>Friday : 8:00 AM - 5:00 PM<br>Saturday : 8:00 AM - 2:00 PM<br>Sunday : Closed <br>", "services": "", "products": "", "video": [], "payment_options": "American Express, Cash, Check, Discover, Mastercard, Visa, ", "yext_id": "2005152"}
{"id": "15520930", "business_name": "Dan Tana's", "address": "9071 Santa Monica Blvd ", "city": "West Hollywood", "state": "CA", "zip": "90069", "lat": "34.081806", "lon": "-118.389084", "phones": ["(310) 275-9444 (Main)"], "category": "Catering Services, Cocktail Lounges, Fine Dining Restaurants, Italian Restaurants, Restaurants, Steak & Chop Restaurants", "business_hour": "Monday : 5:00 PM - 1:00 AM<br>Tuesday : 5:00 PM - 1:00 AM<br>Wednesday : 5:00 PM - 1:00 AM<br>Thursday : 5:00 PM - 1:00 AM<br>Friday : 5:00 PM - 1:00 AM<br>Saturday : 5:00 PM - 1:00 AM<br>Sunday : 5:00 PM - 12:30 AM<br>", "services": "", "products": "", "video": ["http://www.youtube.com/watch?v=LdnjqfJayoI"], "payment_options": "Cash, Visa, Mastercard, American Express, Discover, ", "yext_id": "2406170"}
{"id": "42316718", "business_name": "Handy Appliance Service", "address": "12880 Booth Rd ", "city": "Lovettsville", "state": "VA", "zip": "20180", "lat": "39.258862", "lon": "-77.585678", "phones": ["(703) 297-7857 (Main)"], "category": "Home Appliances Dealers & Service", "business_hour": "Monday : 8:00 AM - 5:00 PM<br>Tuesday : 8:00 AM - 5:00 PM<br>Wednesday : 8:00 AM - 5:00 PM<br>Thursday : 8:00 AM - 5:00 PM<br>Friday : 8:00 AM - 5:00 PM<br>Saturday : Closed <br>Sunday : Closed <br>", "services": "Dryers, Washing Machines, Stove, Refrigerator, Oven, Dishwasher, Microwave, Kitchen Aappliances", "products": "", "video": [], "payment_options": "American Express, Cash, Check, Mastercard, Visa, ", "yext_id": "8088971"}
{"id": "40639393", "business_name": "Teneo Investigations", "address": "205 South Broadway, Suite 300 ", "city": "Los Angeles", "state": "CA", "zip": "90012", "lat": "34.052502", "lon": "-118.247002", "phones": ["(818) 252-9072 (Main)"], "category": "Investigators & Investigation Services, Legal Research, Surveillance Equip., Employment Services, Civil Rights Attorneys & Lawyers", "business_hour": "", "services": "", "products": "California Association Of Licensed Investigators", "video": [], "payment_options": "", "yext_id": "1540949"}
{"id": "16668312", "business_name": "Richard N Deyo Law Offices", "address": "12749 Norwalk Blvd Ste 101 ", "city": "Norwalk", "state": "CA", "zip": "90650", "lat": "33.914371", "lon": "-118.072662", "phones": ["(562) 864-2578 (Main)", "(562) 864-0136 (Fax)"], "category": "Divorce & Family Law Attorneys & Lawyers, Collection Services", "business_hour": "", "services": "", "products": "", "video": [], "payment_options": "", "yext_id": "1741540", "description": "Premier Family Law Legal Services!\n\nOver the course of 30-plus years, you develop a reputation based on your knowledge and courtroom success. Family law attorney Richard N. Deyo has an excellent reputation, earning him an AV rating (the highest rating attainab"}
{"id": "200", "business_name": "Made Up Pizza", "city": "Ashburn", "state": "VA", "phones": ["1:7037238440:Main"], "payment_options": "Visa::Cash, Check::", "description": "<p>First  line<br />Second <b>bold</b> line</p><BR>\r\n &amp; third<br/>", "business_hour": "Monday : 9:00 AM - 5:00 PM\nSunday : Closed \n", "services": "Air &#10;&#13;&#10;Heat", "video": ["https://youtu.be/dUH-HXu_7Ik", "https://www.youtube.com/embed/ySlwBRnDRbk?rel=0", "https://vimeo.com/123", "http://www.youtube.com/watch?v=dUH-HXu_7Ik", "https://www.youtube.com/watch?v=bad"], "group": "Food & Dining"}
`

func TestReadJSONL_DetailFields(t *testing.T) {
	store, err := ReadJSONL(strings.NewReader(detailRecords))
	if err != nil {
		t.Fatal(err)
	}
	get := func(id string) Listing {
		l, ok, _ := store.Get(context.Background(), id)
		if !ok {
			t.Fatalf("listing %s missing", id)
		}
		return l
	}
	week := func(days ...string) []string { return days }
	for _, tt := range []struct {
		id    string
		field string
		got   any
		want  any
	}{
		{"41727058", "hours", get("41727058").Hours, week("Monday : 8:00 AM - 5:00 PM", "Tuesday : 8:00 AM - 5:00 PM", "Wednesday : 8:00 AM - 5:00 PM",
			"Thursday : 8:00 AM - 5:00 PM", "Friday : 8:00 AM - 5:00 PM", "Saturday : 8:00 AM - 2:00 PM", "Sunday : Closed")},
		{"41727058", "phones", get("41727058").Phones, []Phone{{"(571) 271-6500", "+15712716500", "Main"}, {"(703) 723-4000", "+17037234000", "Alt"}}},
		{"41727058", "yextId", get("41727058").YextID, "2005152"},
		{"41727058", "payment", get("41727058").PaymentOptions, []string{"American Express", "Cash", "Check", "Discover", "Mastercard", "Visa"}},
		{"15520930", "videos", get("15520930").Videos, []string{"LdnjqfJayoI"}},
		{"15520930", "last hours line", get("15520930").Hours[6], "Sunday : 5:00 PM - 12:30 AM"},
		{"42316718", "services", get("42316718").Services, "Dryers, Washing Machines, Stove, Refrigerator, Oven, Dishwasher, Microwave, Kitchen Aappliances"},
		{"42316718", "products", get("42316718").Products, ""},
		{"40639393", "products", get("40639393").Products, "California Association Of Licensed Investigators"},
		{"40639393", "hours", get("40639393").Hours, []string{}},
		{"16668312", "description", get("16668312").Description, "Premier Family Law Legal Services!\nOver the course of 30-plus years, you develop a reputation based on your knowledge and courtroom success. Family law attorney Richard N. Deyo has an excellent reputation, earning him an AV rating (the highest rating attainab"},
		{"200", "phones", get("200").Phones, []Phone{{"(703) 723-8440", "+17037238440", "Main"}}},
		{"200", "payment", get("200").PaymentOptions, []string{"Visa", "Cash", "Check"}},
		{"200", "description", get("200").Description, "First line\nSecond bold line\n& third"},
		{"200", "hours", get("200").Hours, week("Monday : 9:00 AM - 5:00 PM", "Sunday : Closed")},
		{"200", "services", get("200").Services, "Air Heat"},
		{"200", "videos", get("200").Videos, []string{"dUH-HXu_7Ik", "ySlwBRnDRbk"}},
	} {
		if !reflect.DeepEqual(tt.got, tt.want) {
			t.Errorf("%s %s = %#v, want %#v", tt.id, tt.field, tt.got, tt.want)
		}
	}
	if g := store.byID["200"].group; g != "food & dining" {
		t.Errorf("group = %q", g)
	}
}

func TestYouTubeIDs(t *testing.T) {
	for _, tt := range []struct {
		in   []string
		want []string
	}{
		{[]string{"http://www.youtube.com/watch?v=LdnjqfJayoI"}, []string{"LdnjqfJayoI"}},
		{[]string{"https://m.youtube.com/watch?feature=share&v=N8hYpdJ-hrU"}, []string{"N8hYpdJ-hrU"}},
		{[]string{"https://youtu.be/HuWUMoVI_is?t=3"}, []string{"HuWUMoVI_is"}},
		{[]string{"https://www.youtube-nocookie.com/embed/PuQkOqQjnTY"}, []string{"PuQkOqQjnTY"}},
		{[]string{"https://vimeo.com/76979871", "https://www.youtube.com/channel/UC123", "not a url", ""}, []string{}},
		{[]string{"https://www.youtube.com/watch?v=short", "https://evil.example.com/watch?v=LdnjqfJayoI"}, []string{}},
	} {
		if got := youTubeIDs(tt.in); !reflect.DeepEqual(got, tt.want) {
			t.Errorf("youTubeIDs(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}

func TestTextLines(t *testing.T) {
	for _, tt := range []struct {
		in   string
		want []string
	}{
		{"Monday : 8:00 AM - 5:00 PM<br>Sunday : Closed <br>", []string{"Monday : 8:00 AM - 5:00 PM", "Sunday : Closed"}},
		{"Monday : 8:00 AM - 5:00 PM\nSunday : Closed\n", []string{"Monday : 8:00 AM - 5:00 PM", "Sunday : Closed"}},
		{"a<BR />b<br/>c\r\n\r\nd", []string{"a", "b", "c", "d"}},
		{`<a href="http://x.example.com/" target="_blank">One Thai Chef</a> is  great`, []string{"One Thai Chef is great"}},
		{"Fish &amp; Chips &#10;&#13;&#10;and more", []string{"Fish & Chips", "and more"}},
		{"&lt;b&gt;not a tag&lt;/b&gt;", []string{"<b>not a tag</b>"}},
		{" <br> ", []string{}},
	} {
		if got := textLines(tt.in); !reflect.DeepEqual(got, tt.want) {
			t.Errorf("textLines(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}

// radiusRecords are made-up listings around Ashburn VA: the city's centre
// is (39.03, -77.48), the mean of its two listings with coordinates.
// Distances from it: Ashburn Hotel A and B 0.87 mi, Sterling Plaza 3.02,
// Sterling 3.2, Leesburg 7.46,
// Germantown MD 14.9, Manassas 19.28, Richmond 103.
const radiusRecords = `{"id":"1","business_name":"Ashburn Hotel B","city":"Ashburn","state":"VA","zip":"20147","lat":"39.02","lon":"-77.47","category":"Hotels"}
{"id":"2","business_name":"Ashburn Hotel A","city":"Ashburn","state":"VA","zip":"20147","lat":"39.04","lon":"-77.49","category":"Hotels"}
{"id":"3","business_name":"Ashburn Inn","city":"Ashburn","state":"VA","zip":"20148","category":"Hotels"}
{"id":"4","business_name":"Sterling Hotel","city":"Sterling","state":"VA","zip":"20164","lat":"39.006","lon":"-77.429","category":"Hotels"}
{"id":"5","business_name":"Aardvark Pizza","city":"Sterling","state":"VA","zip":"20164","lat":"39.006","lon":"-77.429","category":"Pizza, Italian Restaurants"}
{"id":"6","business_name":"Leesburg Thai","city":"Leesburg","state":"VA","zip":"20176","lat":"39.116","lon":"-77.564","category":"Thai Restaurants"}
{"id":"7","business_name":"Germantown Diner","city":"Germantown","state":"MD","zip":"20874","lat":"39.173","lon":"-77.272","category":"Diners","group":"Food & Dining"}
{"id":"8","business_name":"Manassas Hotel","city":"Manassas","state":"VA","zip":"20110","lat":"38.751","lon":"-77.475","category":"Hotels"}
{"id":"9","business_name":"Richmond Hotel","city":"Richmond","state":"VA","zip":"23219","lat":"37.54","lon":"-77.43","category":"Hotels"}
{"id":"10","business_name":"Sterling Plaza Hotel","city":"Sterling","state":"VA","zip":"20147","lat":"39.01","lon":"-77.43","category":"Hotels"}
{"id":"11","business_name":"Washington Hotel","city":"Washington","state":"DC","zip":"20001","category":"Hotels"}
{"id":"12","business_name":"Washington Inn","city":"Washington","state":"PA","zip":"15301","category":"Hotels"}
{"id":"13","business_name":"Washington Lodge","city":"Washington","state":"DC","zip":"20001","category":"Hotels"}
{"id":"14","business_name":"Los Angeles Hotel","city":"Los Angeles","state":"CA","zip":"90012","category":"Hotels"}
`

func radiusStore(t *testing.T) *JSONLStore {
	t.Helper()
	store, err := ReadJSONL(strings.NewReader(radiusRecords))
	if err != nil {
		t.Fatal(err)
	}
	return store
}

func TestSearch_RadiusAndGroups(t *testing.T) {
	store := radiusStore(t)
	ashburn := Location{City: "ashburn", State: "va"}
	ids := func(r Result) []string {
		out := []string{}
		for _, l := range r.Listings {
			out = append(out, l.ID)
		}
		return out
	}
	food := []string{"Pizza", "Thai Restaurants", "food and dining"}
	for _, tt := range []struct {
		name  string
		q     Query
		ids   []string
		total int
	}{
		{"exact city without a radius", Query{Location: ashburn}, []string{"2", "1", "3"}, 3},
		{"radius 15: in-city without coordinates, then nearest first, ties by name",
			Query{Location: ashburn, RadiusMiles: 15}, []string{"3", "2", "1", "10", "5", "4", "6", "7"}, 8},
		{"radius 14 drops Germantown (14.9 mi)", Query{Location: ashburn, RadiusMiles: 14}, []string{"3", "2", "1", "10", "5", "4", "6"}, 7},
		{"radius 25 reaches Manassas, not Richmond", Query{Location: ashburn, RadiusMiles: 25, PageSize: 50}, []string{"3", "2", "1", "10", "5", "4", "6", "7", "8"}, 9},
		{"radius with a keyword", Query{Keyword: "hotel", Location: ashburn, RadiusMiles: 5}, []string{"3", "2", "1", "10", "4"}, 5},
		{"radius page 2", Query{Location: ashburn, RadiusMiles: 15, PageSize: 3, Page: 2}, []string{"10", "5", "4"}, 8},
		{"radius, the largest page", Query{Location: ashburn, RadiusMiles: 15, PageSize: 2, Page: math.MaxInt}, []string{}, 8},
		{"radius, the largest page of the largest size", Query{Location: ashburn, RadiusMiles: 15, PageSize: MaxPageSize, Page: math.MaxInt}, []string{}, 8},
		{"AnyOf: any one term, its words starting words", Query{AnyOf: food, Location: ashburn, RadiusMiles: 15}, []string{"5", "6"}, 2},
		{"Group matches the record group, any case", Query{AnyOf: food, Group: "FOOD & DINING", Location: ashburn, RadiusMiles: 15}, []string{"5", "6", "7"}, 3},
		{"Group alone", Query{Group: "food & dining", Location: ashburn, RadiusMiles: 15}, []string{"7"}, 1},
		{"AnyOf and Keyword both apply", Query{Keyword: "aardvark", AnyOf: food, Location: ashburn, RadiusMiles: 15}, []string{"5"}, 1},
		{"a term must match all its words", Query{AnyOf: []string{"thai pizza"}, Location: ashburn, RadiusMiles: 15}, []string{}, 0},
		{"empty terms are ignored", Query{AnyOf: []string{"", " - "}, Location: Location{City: "Sterling", State: "VA"}}, []string{"5", "4", "10"}, 3},
		{"city without coordinates searches the exact city", Query{Location: Location{City: "Washington", State: "DC"}, RadiusMiles: 15}, []string{"11", "13"}, 2},
		{"unknown city", Query{Location: Location{City: "Nowhere", State: "VA"}, RadiusMiles: 15}, []string{}, 0},
	} {
		t.Run(tt.name, func(t *testing.T) {
			r, err := store.Search(context.Background(), tt.q)
			if err != nil {
				t.Fatal(err)
			}
			if got := ids(r); !reflect.DeepEqual(got, tt.ids) || r.Total != tt.total {
				t.Errorf("got %v total %d, want %v total %d", got, r.Total, tt.ids, tt.total)
			}
			if tt.total > 0 && r.CityName != store.byCity[tt.q.Location.key()][0].City {
				t.Errorf("CityName = %q", r.CityName)
			}
		})
	}
}

func TestExists(t *testing.T) {
	store := radiusStore(t)
	ashburn := Location{City: "ashburn", State: "va"}
	food := []string{"Pizza", "Thai Restaurants", "food and dining"}
	for _, tt := range []struct {
		name string
		q    Query
	}{
		{"exact city", Query{Location: ashburn}},
		{"exact city with a keyword", Query{Keyword: "inn", Location: ashburn}},
		{"exact city, nothing found", Query{Keyword: "pizza", Location: ashburn}},
		{"radius with a keyword", Query{Keyword: "pizza", Location: ashburn, RadiusMiles: 15}},
		{"radius, nothing found", Query{Keyword: "manassas", Location: ashburn, RadiusMiles: 15}},
		{"radius, a group", Query{AnyOf: food, Group: "Food & Dining", Location: ashburn, RadiusMiles: 15}},
		{"radius, a group with nothing found", Query{AnyOf: []string{"Dentists"}, Location: ashburn, RadiusMiles: 15}},
		{"a page past the last", Query{Location: ashburn, Page: 99}},
		{"unknown city", Query{Location: Location{City: "Nowhere", State: "VA"}}},
		{"no location", Query{}},
	} {
		t.Run(tt.name, func(t *testing.T) {
			r, _ := store.Search(context.Background(), tt.q)
			got, err := store.Exists(context.Background(), tt.q)
			if err != nil || got != (r.Total > 0) {
				t.Errorf("Exists = %v, %v; Search found %d", got, err, r.Total)
			}
		})
	}
}

// A category group's members are worked out once per store and group, and
// searched by many requests at once.
func TestSearch_GroupMembersCached(t *testing.T) {
	store := radiusStore(t)
	q := Query{AnyOf: []string{"Pizza", "Thai Restaurants"}, Group: "Food & Dining", Location: Location{City: "Ashburn", State: "VA"}, RadiusMiles: 15}
	var wg sync.WaitGroup
	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if r, _ := store.Search(context.Background(), q); r.Total != 3 {
				t.Errorf("concurrent group search: total %d, want 3", r.Total)
			}
		}()
	}
	wg.Wait()
	n := 0
	store.groups.Range(func(any, any) bool { n++; return true })
	if n != 1 {
		t.Errorf("%d groups kept, want 1", n)
	}
	// The same terms with another label are another group.
	q.Group = ""
	if r, _ := store.Search(context.Background(), q); r.Total != 2 {
		t.Errorf("without the label: total %d, want 2", r.Total)
	}
}

func TestCitiesAndStates(t *testing.T) {
	store := radiusStore(t)
	ctx := context.Background()
	cities, err := store.Cities(ctx, "va")
	want := []CityCount{
		{Name: "Ashburn", Slug: "ashburn", State: "VA", Count: 3},
		{Name: "Leesburg", Slug: "leesburg", State: "VA", Count: 1},
		{Name: "Manassas", Slug: "manassas", State: "VA", Count: 1},
		{Name: "Richmond", Slug: "richmond", State: "VA", Count: 1},
		{Name: "Sterling", Slug: "sterling", State: "VA", Count: 3},
	}
	if err != nil || !reflect.DeepEqual(cities, want) {
		t.Errorf("Cities(va) = %+v, %v; want %+v", cities, err, want)
	}
	if cities, _ := store.Cities(ctx, "WY"); len(cities) != 0 {
		t.Errorf("Cities(WY) = %+v, want none", cities)
	}
	states, err := store.States(ctx)
	wantStates := []StateCount{{"CA", 1}, {"DC", 2}, {"MD", 1}, {"PA", 1}, {"VA", 9}}
	if err != nil || !reflect.DeepEqual(states, wantStates) {
		t.Errorf("States = %+v, %v; want %+v", states, err, wantStates)
	}
}

func TestResolveLocation(t *testing.T) {
	store := radiusStore(t)
	ashburn := Location{City: "Ashburn", State: "VA"}
	for _, tt := range []struct {
		in   string
		want Location
		ok   bool
	}{
		{"Ashburn, VA", ashburn, true},
		{"ashburn,va", ashburn, true},
		{"VA, Ashburn", ashburn, true},
		{"VA,Ashburn/", ashburn, true},
		{"va%2CAshburn%2F", ashburn, true},
		{"Ashburn VA", ashburn, true},
		{"ashburn-va", ashburn, true},
		{"Los+Angeles,+CA", Location{"Los Angeles", "CA"}, true},
		{"los-angeles, ca", Location{"Los Angeles", "CA"}, true},
		{"Los%20Angeles%20CA", Location{"Los Angeles", "CA"}, true},
		{"20164", Location{"Sterling", "VA"}, true},
		{"20147", ashburn, true}, // two Ashburn listings, one Sterling
		{"20147-1234", ashburn, true},
		{"99999", Location{}, false},
		{"Sterling", Location{"Sterling", "VA"}, true},
		{"  ASHBURN/ ", ashburn, true},
		{"Washington", Location{"Washington", "DC"}, true}, // DC has more listings than PA
		{"Washington PA", Location{"Washington", "PA"}, true},
		{"Nowhere, VA", Location{"Nowhere", "VA"}, true}, // well-formed, no listings: as typed
		{"VA, Nowhere", Location{"Nowhere", "VA"}, true},
		{"Nowhere TX", Location{"Nowhere", "TX"}, true},
		{"Nowhere", Location{}, false},
		{"Delhi, DL", Location{}, false},
		{"", Location{}, false},
		{" / ", Location{}, false},
		// A trailing country or zip is dropped.
		{"Ashburn, VA, USA", ashburn, true},
		{"Ashburn, VA, US", ashburn, true},
		{"Ashburn VA 20147", ashburn, true},
		{"Ashburn, VA 20147-1234", ashburn, true},
		{"Ashburn, VA 20147, United States", ashburn, true},
		{"ashburn va usa/", ashburn, true},
		{"20147, USA", ashburn, true},
		{"USA", Location{}, false},
	} {
		got, ok, err := store.ResolveLocation(context.Background(), tt.in)
		if err != nil || got != tt.want || ok != tt.ok {
			t.Errorf("ResolveLocation(%q) = %+v, %v, %v; want %+v, %v", tt.in, got, ok, err, tt.want, tt.ok)
		}
	}
}

func TestMatcher(t *testing.T) {
	pizza := Listing{Name: "Pizza Time", Categories: []string{"American Restaurants", "Pizza"}}
	diner := Listing{Name: "Germantown Diner", Categories: []string{"Diners"}, Group: "Food & Dining"}
	food := []string{"Pizza", "Thai Restaurants"}
	for _, tt := range []struct {
		name string
		q    Query
		l    Listing
		want bool
	}{
		{"empty query", Query{}, pizza, true},
		{"keyword", Query{Keyword: "american pizza"}, pizza, true},
		{"keyword, a word missing", Query{Keyword: "thai pizza"}, pizza, false},
		{"a group term", Query{AnyOf: food}, pizza, true},
		{"the record's group, any case", Query{AnyOf: food, Group: "FOOD & DINING"}, diner, true},
		{"not in the group", Query{AnyOf: food, Group: "Food & Dining"}, Listing{Name: "Thai Massage", Categories: []string{"Massage"}}, false},
		{"location ignored", Query{AnyOf: food, Location: Location{City: "Nowhere", State: "VA"}}, pizza, true},
		// Every word of a group term must start a word, in any order.
		{"a term inside a word", Query{AnyOf: []string{"Arts"}}, Listing{Name: "Joe's", Categories: []string{"Auto Parts"}}, false},
		{"a term as a whole word", Query{AnyOf: []string{"Arts"}}, Listing{Name: "Joe's", Categories: []string{"Performing Arts"}}, true},
		{"a term's words apart", Query{AnyOf: []string{"Pet Sitting"}}, Listing{Name: "Cupid Pets", Categories: []string{"Pet & Animal Sitting"}}, true},
		{"a term's words apart, & in the text", Query{AnyOf: []string{"Immigration Naturalization"}}, Listing{Name: "A", Categories: []string{"Immigration & Naturalization Attorneys & Lawyers"}}, true},
		{"a term word starting a longer word", Query{AnyOf: []string{"Appliance Dealers"}}, Listing{Name: "A", Categories: []string{"Home Appliances Dealers & Service"}}, true},
		{"a term's words in another order", Query{AnyOf: []string{"Thai Restaurants"}}, Listing{Name: "B", Categories: []string{"Restaurants (Thai)"}}, true},
		{"a term's word missing", Query{AnyOf: []string{"Thai Restaurants"}}, Listing{Name: "B", Categories: []string{"Thai Massage"}}, false},
		{"a term, & as and", Query{AnyOf: []string{"Bed & Breakfast"}}, Listing{Name: "Rose Bed and Breakfast"}, true},
		{"a term word ending a word", Query{AnyOf: []string{"Pizza"}}, Listing{Name: "Mozzapizza Bar"}, false},
		{"keyword matches inside words", Query{Keyword: "arts"}, Listing{Name: "Joe's", Categories: []string{"Auto Parts"}}, true},
	} {
		if got := NewMatcher(tt.q).Matches(tt.l); got != tt.want {
			t.Errorf("%s: %v, want %v", tt.name, got, tt.want)
		}
	}
}
