package routes

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"sync"
	"testing"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/listings"
	"github.com/julienschmidt/httprouter"
	"github.com/spf13/viper"
)

// testListingAPI is test data only: listing API answers shaped like the dev
// API's (lp-2742 from its getBusinessDetails), by action.
var testListingAPI = map[string]string{
	"getBusinessDetails": `{"success":true,"data":{"id":"lp-2742","name":"Z Dental Group","address":"6320 Commodore Sloat Drive","city":"Los Angeles","state":"CA","zip":"90048","lat":34.073253,"lon":-118.377034,"phones":[{"number":"(323) 936-9997","label":"Main"}],"categories":["Dentists"],"hours":[],"source":"localpages","is_verified":true,"type":"lp"}}`,
	"getCities":          `{"success":true,"data":{"state":"CA","total":2,"cities":[{"name":"Los Angeles","slug":"los-angeles","count":166863,"lat":34.04,"lon":-118.29},{"name":"Empty Town","slug":"empty-town","count":1,"lat":34.1,"lon":-118.1}]}}`,
}

// fakeListingAPI serves testListingAPI; getBusinessList answers by city: Los
// Angeles has lp-2742, Empty Town none, other cities 404.
func fakeListingAPI(t *testing.T) (*httptest.Server, *[]url.Values) {
	t.Helper()
	var mu sync.Mutex
	requests := []url.Values{}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query()
		mu.Lock()
		requests = append(requests, q)
		mu.Unlock()
		if r.Header.Get("X-API-KEY") != "test-key" {
			w.WriteHeader(http.StatusForbidden)
			w.Write([]byte(`{"success":false,"error":"Invalid or missing API key."}`))
			return
		}
		if q.Get("action") == "getBusinessList" {
			switch q.Get("city") {
			case "Los Angeles":
				var detail struct {
					Data json.RawMessage `json:"data"`
				}
				json.Unmarshal([]byte(testListingAPI["getBusinessDetails"]), &detail)
				w.Write([]byte(`{"success":true,"location":{"city":"Los Angeles","state":"CA"},"pagination":{"total":1,"total_pages":1},"data":[` + string(detail.Data) + `]}`))
			case "Empty Town":
				w.Write([]byte(`{"success":true,"location":{"city":"Empty Town","state":"CA"},"pagination":{"total":0,"total_pages":0},"data":[]}`))
			default:
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte(`{"success":false,"error":"Location not found."}`))
			}
			return
		}
		body, ok := testListingAPI[q.Get("action")]
		if !ok || q.Get("action") == "getBusinessDetails" && q.Get("id") != "lp-2742" {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(`{"success":false,"error":"Business not found."}`))
			return
		}
		w.Write([]byte(body))
	}))
	t.Cleanup(server.Close)
	return server, &requests
}

func TestDirectory_ListingAPI(t *testing.T) {
	server, requests := fakeListingAPI(t)
	useTestListings(t, listings.NewAPIStore(server.URL, "test-key", time.Minute, listingsSite))
	config := testClientConfig(t, testDirectoryConfig)
	config.ViperConfig.Set("_client", "localpages")

	// The data API serves a verified listing by its lp- id.
	rec := serveWith(DataListingsHandler(), config, "/data/listings/lp-2742", httprouter.Params{{Key: "id", Value: "lp-2742"}})
	var detail struct {
		Listing listings.Listing   `json:"listing"`
		Nearby  []listings.Listing `json:"nearby"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &detail); err != nil || rec.Code != http.StatusOK {
		t.Fatalf("/data/listings/lp-2742: %d %s", rec.Code, rec.Body)
	}
	if detail.Listing.URL != "/ca/los-angeles/lp-2742-z-dental-group" || detail.Nearby == nil || len(detail.Nearby) != 0 {
		t.Errorf("listing %q, nearby %v (itself left out)", detail.Listing.URL, detail.Nearby)
	}
	for _, q := range *requests {
		if q.Get("site") != "localpages" {
			t.Errorf("request %v sent without site=localpages", q)
		}
	}
	if rec := serveWith(DataListingsHandler(), config, "/data/listings/lp-x", httprouter.Params{{Key: "id", Value: "lp-x"}}); rec.Code != http.StatusNotFound {
		t.Errorf("/data/listings/lp-x: %d", rec.Code)
	}

	handler := notFoundHandler(pageTemplatesFrom("../web/templates"))
	for _, tt := range []struct {
		name     string
		path     string
		status   int
		location string
	}{
		{"verified listing", "/ca/los-angeles/lp-2742-z-dental-group", http.StatusOK, ""},
		{"verified listing, other slug", "/ca/los-angeles/lp-2742-old-name", http.StatusMovedPermanently, "/ca/los-angeles/lp-2742-z-dental-group"},
		{"unknown verified listing", "/ca/los-angeles/lp-9-x", http.StatusNotFound, ""},
		{"city page", "/ca/los-angeles", http.StatusOK, ""},
		{"city the API knows, no listings", "/ca/empty-town", http.StatusNotFound, ""},
		{"city the API doesn't know", "/ca/nowhere", http.StatusNotFound, ""},
	} {
		rec := serveWith(handler, config, tt.path, nil)
		if rec.Code != tt.status || rec.Header().Get("Location") != tt.location {
			t.Errorf("%s: %s = %d %q; want %d %q", tt.name, tt.path, rec.Code, rec.Header().Get("Location"), tt.status, tt.location)
		}
	}
}

func TestInitListingsStore(t *testing.T) {
	orig := listingsStore
	t.Cleanup(func() {
		listingsStore = orig
		for _, key := range []string{"listings_api_url", "listings_api_key", "listings_jsonl_path"} {
			viper.Set(key, "")
		}
	})
	for _, tt := range []struct {
		url, key string
		api      bool
	}{
		{"https://api.example.test/businesslist/", "k", true},
		{"https://api.example.test/businesslist/", "", false},
		{"", "k", false},
	} {
		viper.Set("listings_api_url", tt.url)
		viper.Set("listings_api_key", tt.key)
		viper.Set("listings_jsonl_path", "")
		InitListingsStore()
		_, isAPI := listingsStore.(*listings.APIStore)
		if isAPI != tt.api || !tt.api && listingsStore.Available() {
			t.Errorf("url %q key %q: store %T, want the API store %v", tt.url, tt.key, listingsStore, tt.api)
		}
	}
	if site := listingsSite(context.Background()); site != "" {
		t.Errorf("listingsSite without a config = %q", site)
	}
}

// TestLocalpagesLegacyVerifiedListing reads the real localpages config: a
// live verified-listing URL lands on the listing's URL in one hop.
func TestLocalpagesLegacyVerifiedListing(t *testing.T) {
	server, _ := fakeListingAPI(t)
	useTestListings(t, listings.NewAPIStore(server.URL, "test-key", time.Minute, listingsSite))
	raw, err := os.ReadFile("../client_configs/localpages.json")
	if err != nil {
		t.Fatal(err)
	}
	config := testClientConfig(t, string(raw))
	config.ViperConfig.Set("_client", "localpages")
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))

	rec := serveWith(handler, config, "/ca/los-angeles/lp-2742-z-dental-group.html", nil)
	if want := "/ca/los-angeles/lp-2742-z-dental-group"; rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != want {
		t.Errorf("live lp URL: %d %q, want 301 %q", rec.Code, rec.Header().Get("Location"), want)
	}
}
