package listings

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strings"
	"sync"
	"testing"
	"time"
)

// apiDetail is test data only: the dev API's getBusinessDetails answer for
// 15427697, its description and images shortened.
const apiDetail = `{"success":true,"data":{"id":"15427697","name":"Downtown Dental Los Angeles","address":"255 S Grand Ave #204","city":"Los Angeles","state":"CA","zip":"90012","lat":34.053665,"lon":-118.251472,"phones":[{"number":"(213) 620-5777","label":"Main"}],"website":"http://www.downtowndentalla.com/","categories":["Dentists","Cosmetic Dentists"],"description":"Creating heavenly smiles<br>in Downtown Los Angeles","hours":[{"day":"Monday","open":"07:30","close":"16:00"},{"day":"Friday","open":"00:00","close":"12:30"},{"day":"Saturday","closed":true},{"day":"Sunday","open":"","close":""}],"services":"","products":"","payment_options":["American Express","Cash"," "],"special_offer":"New Patients Welcome","special_offer_url":"http://vccy4a.yext-wraps.com/plclick?pid=EAzeX9WdJk","images":["https://a.mktgcdn.com/p/A3RI/250x250.png","http://a.mktgcdn.com/p/HNVc/619x387.jpg"],"videos":["lfJhemkBZvg","bad"],"yext_id":"1863193","source":"yext","is_verified":false,"type":"lpd"}}`

// apiSearch is test data only, shaped like the dev API's getBusinessList
// answer: a verified record without phones and 15524866's escaped services.
const apiSearch = `{"success":true,"location":{"city":"Los Angeles","state":"CA","lat":34.042815,"lon":-118.298568},"pagination":{"page":2,"per_page":2,"count":2,"total":3,"total_pages":2},"data":[{"id":"lp-2742","name":"Los Angeles Dentist | Z Dental Group","city":"Los Angeles","state":"CA","lat":34.073253,"lon":-118.377034,"phones":[],"website":null,"categories":["Health & Medicine"],"hours":[],"special_offer":null,"special_offer_url":null,"source":"localpages","is_verified":true,"type":"lp"},{"id":"15524866","name":"J.Crew","city":"Los Angeles","state":"CA","services":"Women\\'s, Men\\'s, crewcuts","phones":[{"number":"(310) 552-5320","label":"Main"}]},{"id":"bad id","name":"Dropped","city":"Los Angeles","state":"CA"}]}`

// fakeAPI serves the listing API from answers keyed by action; it records
// each request.
type fakeAPI struct {
	mu       sync.Mutex
	answers  map[string]string // action → body; missing: 404
	status   int               // when set, every answer's status
	requests []fakeRequest
}

type fakeRequest struct {
	method string
	key    string
	params url.Values
	body   map[string]interface{}
}

func (f *fakeAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	req := fakeRequest{method: r.Method, key: r.Header.Get("X-API-KEY"), params: r.URL.Query()}
	action := req.params.Get("action")
	if r.Method == http.MethodPost {
		data, _ := io.ReadAll(r.Body)
		json.Unmarshal(data, &req.body)
		action, _ = req.body["action"].(string)
	}
	f.mu.Lock()
	f.requests = append(f.requests, req)
	body, ok := f.answers[action]
	status := f.status
	f.mu.Unlock()
	switch {
	case status != 0:
		w.WriteHeader(status)
		w.Write([]byte(`{"success":false,"error":"Invalid or missing API key."}`))
	case !ok:
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte(`{"success":false,"error":"Location not found."}`))
	default:
		w.Write([]byte(body))
	}
}

func (f *fakeAPI) calls() []fakeRequest {
	f.mu.Lock()
	defer f.mu.Unlock()
	return append([]fakeRequest{}, f.requests...)
}

// actionCalls are the requests of one action.
func (f *fakeAPI) actionCalls(action string) []fakeRequest {
	out := []fakeRequest{}
	for _, c := range f.calls() {
		if c.params.Get("action") == action || c.body["action"] == action {
			out = append(out, c)
		}
	}
	return out
}

type testSiteKey struct{}

// withSite is ctx naming the site the test store sends.
func withSite(ctx context.Context, site string) context.Context {
	return context.WithValue(ctx, testSiteKey{}, site)
}

func apiStore(t *testing.T, answers map[string]string) (*APIStore, *fakeAPI) {
	t.Helper()
	fake := &fakeAPI{answers: answers}
	server := httptest.NewServer(fake)
	t.Cleanup(server.Close)
	site := func(ctx context.Context) string {
		site, _ := ctx.Value(testSiteKey{}).(string)
		return site
	}
	return NewAPIStore(server.URL+"/businesslist/", "test-key", time.Minute, site), fake
}

func TestAPIStore_Get(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getBusinessDetails": apiDetail})
	ctx := withSite(context.Background(), "cured")
	l, found, err := store.Get(ctx, "15427697")
	if err != nil || !found {
		t.Fatalf("Get = found %v, err %v", found, err)
	}
	lat, lon := 34.053665, -118.251472
	want := Listing{
		ID:             "15427697",
		Name:           "Downtown Dental Los Angeles",
		URL:            "/ca/los-angeles/15427697-downtown-dental-los-angeles",
		Address:        "255 S Grand Ave #204",
		City:           "Los Angeles",
		State:          "CA",
		Zip:            "90012",
		Lat:            &lat,
		Lon:            &lon,
		Phones:         []Phone{{Number: "(213) 620-5777", Tel: "+12136205777", Label: "Main"}},
		Website:        "http://www.downtowndentalla.com/",
		Categories:     []string{"Dentists", "Cosmetic Dentists"},
		Description:    "Creating heavenly smiles\nin Downtown Los Angeles",
		Hours:          []string{"Monday : 7:30 AM - 4:00 PM", "Friday : 12:00 AM - 12:30 PM", "Saturday : Closed"},
		PaymentOptions: []string{"American Express", "Cash"},
		SpecialOffer:   &SpecialOffer{Text: "New Patients Welcome", URL: "http://vccy4a.yext-wraps.com/plclick?pid=EAzeX9WdJk"},
		Images:         []string{"https://a.mktgcdn.com/p/A3RI/250x250.png", "https://a.mktgcdn.com/p/HNVc/619x387.jpg"},
		Videos:         []string{"lfJhemkBZvg"},
		YextID:         "1863193",
		Source:         "yext",
	}
	if !reflect.DeepEqual(l, want) {
		t.Errorf("Get =\n%+v\nwant\n%+v", l, want)
	}
	calls := fake.calls()
	if len(calls) != 1 {
		t.Fatalf("%d requests, want 1", len(calls))
	}
	c := calls[0]
	if c.method != http.MethodGet || c.key != "test-key" || c.params.Get("id") != "15427697" || c.params.Get("site") != "cured" || c.params.Get("api_key") != "" {
		t.Errorf("request = %s key %q params %v", c.method, c.key, c.params)
	}
}

func TestAPIStore_GetNotFound(t *testing.T) {
	store, fake := apiStore(t, map[string]string{})
	for _, id := range []string{"999", "lp-999", "999"} {
		if _, found, err := store.Get(context.Background(), id); found || err != nil {
			t.Errorf("Get(%q) = found %v, err %v; want not found", id, found, err)
		}
	}
	// The second 999 comes from the cache.
	if n := len(fake.calls()); n != 2 {
		t.Errorf("%d requests, want 2", n)
	}
	for _, id := range []string{"", "abc", "lp-", "12 3", "lp-2742-x", "../1"} {
		if _, found, err := store.Get(context.Background(), id); found || err != nil {
			t.Errorf("Get(%q) = found %v, err %v; want not found", id, found, err)
		}
	}
	if n := len(fake.calls()); n != 2 {
		t.Errorf("an invalid id was sent: %d requests", n)
	}
}

func TestAPIStore_Search(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getBusinessList": apiSearch})
	ctx := withSite(context.Background(), "localpages")
	q := Query{Keyword: "  dentist  care ", Location: Location{City: "los-angeles", State: "ca"}, RadiusMiles: 62.5, Page: 2, PageSize: 2}
	result, err := store.Search(ctx, q)
	if err != nil {
		t.Fatal(err)
	}
	if result.Total != 3 || result.TotalPages != 2 || result.Page != 2 || result.PageSize != 2 || result.CityName != "Los Angeles" {
		t.Errorf("result = %+v", result)
	}
	if len(result.Listings) != 2 {
		t.Fatalf("%d listings, want 2 (the bad id dropped)", len(result.Listings))
	}
	if lp := result.Listings[0]; lp.ID != "lp-2742" || lp.URL != "/ca/los-angeles/lp-2742-los-angeles-dentist-z-dental-group" ||
		lp.Website != "" || lp.SpecialOffer != nil || lp.Source != "localpages" || len(lp.Phones) != 0 || lp.Hours == nil {
		t.Errorf("verified listing = %+v", lp)
	}
	if got := result.Listings[1].Services; got != "Women's, Men's, crewcuts" {
		t.Errorf("services = %q", got)
	}
	want := url.Values{
		"action": {"getBusinessList"}, "keyword": {"dentist care"}, "city": {"los angeles"}, "state": {"CA"},
		"radius": {"62.5"}, "page": {"2"}, "per_page": {"2"}, "site": {"localpages"},
	}
	if c := fake.actionCalls("getBusinessList")[0]; c.method != http.MethodGet || !reflect.DeepEqual(c.params, want) {
		t.Errorf("request = %s %v, want GET %v", c.method, c.params, want)
	}

	exists, err := store.Exists(ctx, q)
	if !exists || err != nil {
		t.Errorf("Exists = %v, %v", exists, err)
	}
	if c := fake.actionCalls("getBusinessList")[1]; c.params.Get("page") != "1" || c.params.Get("per_page") != "1" {
		t.Errorf("Exists request = %v", c.params)
	}
}

func TestAPIStore_SearchCategories(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getBusinessList": apiSearch})
	terms := []string{"Dentists", " dentists", "", "Pediatric  Dentistry"}
	for i := 0; i < 400; i++ {
		terms = append(terms, "Term "+strings.Repeat("x", i+1))
	}
	q := Query{AnyOf: terms, Group: "Health", Location: Location{City: "Ashburn", State: "VA"}}
	if _, err := store.Search(context.Background(), q); err != nil {
		t.Fatal(err)
	}
	c := fake.actionCalls("getBusinessList")[0]
	if c.method != http.MethodPost || c.key != "test-key" {
		t.Fatalf("request = %s key %q, want a POST", c.method, c.key)
	}
	categories, _ := c.body["categories"].([]interface{})
	if len(categories) != apiMaxCategories || categories[0] != "Dentists" || categories[1] != "Pediatric Dentistry" {
		t.Errorf("categories = %d items, first %v", len(categories), categories[:2])
	}
	for _, name := range []string{"page", "per_page", "city", "state"} {
		if _, ok := c.body[name].(string); !ok {
			t.Errorf("%s = %#v, want a string", name, c.body[name])
		}
	}
	if _, ok := c.body["group"]; ok {
		t.Error("group was sent")
	}
}

func TestAPIStore_SearchEmpty(t *testing.T) {
	store, fake := apiStore(t, map[string]string{})
	for _, q := range []Query{
		{Location: Location{City: "Nowhereville", State: "CA"}},
		{Location: Location{}},
		{Location: Location{City: "Ashburn", State: "VA"}, Page: apiMaxPage + 1},
	} {
		result, err := store.Search(context.Background(), q)
		if err != nil || result.Total != 0 || result.Listings == nil || result.CityName != "" {
			t.Errorf("Search(%+v) = %+v, %v; want an empty result", q, result, err)
		}
	}
	if n := len(fake.actionCalls("getBusinessList")); n != 1 {
		t.Errorf("%d searches sent, want 1 (no location or page past 1000: none)", n)
	}
}

func TestAPIStore_Errors(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getBusinessDetails": apiDetail})
	fake.status = http.StatusForbidden
	if _, _, err := store.Get(context.Background(), "15427697"); err == nil || !strings.Contains(err.Error(), "Invalid or missing API key") {
		t.Errorf("Get on 403: err = %v", err)
	}
	if _, err := store.Search(context.Background(), Query{Location: Location{City: "Ashburn", State: "VA"}}); err == nil {
		t.Error("Search on 403: no error")
	}
	// An error isn't cached.
	fake.status = 0
	if _, found, err := store.Get(context.Background(), "15427697"); !found || err != nil {
		t.Errorf("Get after the 403 = found %v, err %v", found, err)
	}

	broken, _ := apiStore(t, map[string]string{"getBusinessDetails": `{"success":true,"data":`})
	if _, _, err := broken.Get(context.Background(), "1"); err == nil {
		t.Error("Get of a broken answer: no error")
	}
}

func TestAPIStore_CacheBySite(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getBusinessDetails": apiDetail})
	for _, site := range []string{"localpages", "cured", "localpages"} {
		if _, _, err := store.Get(withSite(context.Background(), site), "15427697"); err != nil {
			t.Fatal(err)
		}
	}
	if n := len(fake.calls()); n != 2 {
		t.Errorf("%d requests, want 2 (one per site)", n)
	}
}

func TestClockTime(t *testing.T) {
	for in, want := range map[string]string{"07:30": "7:30 AM", "00:00": "12:00 AM", "12:00": "12:00 PM", "23:59": "11:59 PM"} {
		if got, ok := clockTime(in); !ok || got != want {
			t.Errorf("clockTime(%q) = %q, %v; want %q", in, got, ok, want)
		}
	}
	for _, in := range []string{"", "-", "24:00", "7:30 AM"} {
		if got, ok := clockTime(in); ok {
			t.Errorf("clockTime(%q) = %q; want not ok", in, got)
		}
	}
}

// apiCities is test data only: entries of the dev API's getCities answers
// (CA, MO, TX), junk ones included.
const apiCities = `{"success":true,"data":{"state":"MO","total":12,"cities":[
{"name":"63074","slug":"63074","count":1,"lat":null,"lon":null},
{"name":"Saint Louis","slug":"saint-louis","count":67303,"lat":38.63,"lon":-90.28},
{"name":"Saint Louis,","slug":"saint-louis","count":1,"lat":38.63,"lon":-90.28},
{"name":"St. Louis","slug":"st-louis","count":2918,"lat":38.62,"lon":-90.19},
{"name":"St.Louis","slug":"st-louis","count":10,"lat":38.62,"lon":-90.19},
{"name":"Lee’s Summit","slug":"lees-summit","count":5000,"lat":38.91,"lon":-94.38},
{"name":"Town & Country","slug":"town-country","count":300,"lat":38.62,"lon":-90.46},
{"name":"<br>Newport Beach","slug":"br-newport-beach","count":1,"lat":33.6,"lon":-117.9},
{"name":"?Dallas","slug":"dallas","count":1,"lat":32.7,"lon":-96.7},
{"name":"Â Kansas City","slug":"kansas-city","count":9,"lat":39.1,"lon":-94.5},
{"name":"kansas  city","slug":"kansas-city","count":36359,"lat":39.1,"lon":-94.5},
{"name":"Adrian","slug":"adrian","count":181,"lat":null,"lon":-94.3},
{"name":"Lenexa, Kansas","slug":"lenexa-kansas","count":2,"lat":38.9,"lon":-94.7},
{"name":"Abilene (Taylor Co)","slug":"abilene-taylor-co","count":5,"lat":32.4,"lon":-99.7}]}}`

func TestAPIStore_Cities(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getCities": apiCities})
	ctx := withSite(context.Background(), "accoona")
	cities, err := store.Cities(ctx, "mo")
	if err != nil {
		t.Fatal(err)
	}
	want := []CityCount{
		{Name: "kansas city", Slug: "kansas-city", State: "MO", Count: 36359},
		{Name: "Lee’s Summit", Slug: "lee-s-summit", State: "MO", Count: 5000},
		{Name: "Saint Louis", Slug: "saint-louis", State: "MO", Count: 67303},
		{Name: "St. Louis", Slug: "st-louis", State: "MO", Count: 2918},
		{Name: "Town & Country", Slug: "town-country", State: "MO", Count: 300},
	}
	if !reflect.DeepEqual(cities, want) {
		t.Errorf("Cities =\n%+v\nwant\n%+v", cities, want)
	}
	// The list is kept; an unknown state sends nothing.
	cities[0].Name = "changed"
	again, _ := store.Cities(ctx, "MO")
	none, _ := store.Cities(ctx, "zz")
	calls := fake.actionCalls("getCities")
	if len(calls) != 1 || calls[0].params.Get("state") != "MO" || calls[0].params.Get("site") != "accoona" || again[0].Name != "kansas city" || len(none) != 0 {
		t.Errorf("%d getCities sent (%v), again %+v, zz %+v", len(calls), calls, again[0], none)
	}
	// Each site has its own list.
	store.Cities(withSite(context.Background(), "localpages"), "MO")
	if n := len(fake.actionCalls("getCities")); n != 2 {
		t.Errorf("%d getCities sent, want 2", n)
	}
}

func TestAPIStore_SearchCityName(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getCities": apiCities, "getBusinessList": apiSearch})
	for slug, want := range map[string]string{"saint-louis": "Saint Louis", "St Louis": "St. Louis", "lee-s-summit": "Lee’s Summit", "new-town": "new town"} {
		fake.requests = nil
		if _, err := store.Search(context.Background(), Query{Location: Location{City: slug, State: "mo"}}); err != nil {
			t.Fatal(err)
		}
		if got := fake.actionCalls("getBusinessList")[0].params.Get("city"); got != want {
			t.Errorf("city %q sent as %q, want %q", slug, got, want)
		}
	}
}

func TestAPIStore_States(t *testing.T) {
	store, _ := apiStore(t, map[string]string{"getStates": `{"success":true,"data":{"states":[{"code":"va","name":"Virginia","count":9},{"code":"AK","name":"Alaska","count":51057},{"code":"ZZ","count":3},{"code":"DC","count":0}]}}`})
	states, err := store.States(context.Background())
	want := []StateCount{{Code: "AK", Count: 51057}, {Code: "VA", Count: 9}}
	if err != nil || !reflect.DeepEqual(states, want) {
		t.Errorf("States = %+v, %v; want %+v", states, err, want)
	}
}

func TestAPIStore_ResolveLocation(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getCities": apiCities})
	fake.answers["getBusinessList"] = `{"success":true,"location":{"city":"Ashburn","state":"VA","lat":39.03,"lon":-77.48},"pagination":{"total":1},"data":[]}`
	for in, want := range map[string]Location{
		"20147":                {City: "Ashburn", State: "VA"},
		"saint louis, mo":      {City: "Saint Louis", State: "MO"},
		"MO, St Louis":         {City: "St. Louis", State: "MO"},
		"Lee s Summit MO":      {City: "Lee’s Summit", State: "MO"},
		"Kansas+City%2C+MO/":   {City: "kansas city", State: "MO"},
		"Nowhere, MO":          {City: "Nowhere", State: "MO"},
		"Saint Louis, MO, USA": {City: "Saint Louis", State: "MO"},
	} {
		got, ok, err := store.ResolveLocation(context.Background(), in)
		if err != nil || !ok || got != want {
			t.Errorf("ResolveLocation(%q) = %+v, %v, %v; want %+v", in, got, ok, err, want)
		}
	}
	if zips := fake.actionCalls("getBusinessList"); len(zips) != 1 || zips[0].params.Get("zip") != "20147" || zips[0].params.Get("per_page") != "1" {
		t.Errorf("zip requests = %v", zips)
	}
	for _, in := range []string{"", "Saint Louis", "Ashburn, ZZ"} {
		if got, ok, err := store.ResolveLocation(context.Background(), in); ok || err != nil {
			t.Errorf("ResolveLocation(%q) = %+v, %v, %v; want none", in, got, ok, err)
		}
	}
	delete(fake.answers, "getBusinessList")
	if got, ok, _ := store.ResolveLocation(context.Background(), "99999"); ok {
		t.Errorf("unknown zip = %+v", got)
	}
}

func TestAPIStore_Nearby(t *testing.T) {
	store, fake := apiStore(t, map[string]string{"getBusinessList": apiSearch})
	self := Listing{ID: "lp-2742", City: "Los Angeles", State: "CA", Categories: []string{"Dentists", "Orthodontists"}}
	nearby, err := store.Nearby(context.Background(), self, "", 5)
	if err != nil || len(nearby) != 1 || nearby[0].ID != "15524866" {
		t.Fatalf("Nearby = %+v, %v; want 15524866 only (self left out)", nearby, err)
	}
	c := fake.actionCalls("getBusinessList")[0]
	if c.method != http.MethodGet || c.params.Get("keyword") != "Dentists" || c.params.Get("per_page") != "6" || c.params.Get("radius") != "" {
		t.Errorf("Nearby request = %s %v", c.method, c.params)
	}
	if nearby, _ := store.Nearby(context.Background(), Listing{ID: "1", City: "Los Angeles", State: "CA", Categories: []string{"Dentists"}}, "", 1); len(nearby) != 1 {
		t.Errorf("Nearby(n=1) = %d listings", len(nearby))
	}
	if nearby, _ := store.Nearby(context.Background(), self, "  pizza ", 5); len(nearby) != 1 || fake.actionCalls("getBusinessList")[2].params.Get("keyword") != "pizza" {
		t.Errorf("Nearby with a keyword = %+v", nearby)
	}
	fake.requests = nil
	if nearby, err := store.Nearby(context.Background(), Listing{ID: "1", City: "Los Angeles", State: "CA"}, "", 5); err != nil || len(nearby) != 0 || nearby == nil {
		t.Errorf("Nearby without categories = %v, %v", nearby, err)
	}
	if n := len(fake.actionCalls("getBusinessList")); n != 0 {
		t.Errorf("Nearby without categories sent %d searches", n)
	}
}
