package routes

import (
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"strings"

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

// listingsCacheControl is the browser/CDN lifetime of a listings API answer.
const listingsCacheControl = "public, max-age=600"

type listingLocationJSON struct {
	City  string `json:"city"`
	State string `json:"state"`
	Label string `json:"label"`
	Path  string `json:"path"`
}

type listingSearchJSON struct {
	Keyword    string              `json:"keyword"`
	Category   string              `json:"category"` // the site category s names (its slug), else ""
	Location   listingLocationJSON `json:"location"`
	Listings   []listings.Listing  `json:"listings"`
	Total      int                 `json:"total"`
	Page       int                 `json:"page"`
	PageSize   int                 `json:"pageSize"`
	TotalPages int                 `json:"totalPages"`
}

type listingStateJSON struct {
	Code  string `json:"code"`
	Name  string `json:"name"`
	Path  string `json:"path"`
	Count int    `json:"count,omitempty"`
}

type listingStatesJSON struct {
	States []listingStateJSON `json:"states"`
}

type listingCityJSON struct {
	Name  string `json:"name"`
	Slug  string `json:"slug"`
	Path  string `json:"path"`
	Count int    `json:"count"`
}

type listingCitiesJSON struct {
	State  listingStateJSON  `json:"state"`
	Cities []listingCityJSON `json:"cities"`
}

type listingDetailJSON struct {
	Listing listings.Listing   `json:"listing"`
	Nearby  []listings.Listing `json:"nearby"`
}

type listingsErrorJSON struct {
	Error string `json:"error"`
}

// DataListingsHandler serves the directory sites' listings API:
//
//	GET /data/listings/search?s={keyword}&loc={location}&page={n}&pageSize={n}
//	GET /data/listings/states
//	GET /data/listings/cities?state={st}
//	GET /data/listings/{id}
//
// (one route, as httprouter can't have /search beside /:id). loc goes through
// the store's ResolveLocation; empty or unresolvable means the site's
// directory.defaultLocation. s naming a site category (label, slug or
// keyword) searches that category, its slug in "category". The page size is
// directory.pageSize, or pageSize when smaller. A listing comes with up to
// directory.nearbyCount nearby listings. Unknown id or state, or a site that
// isn't a directory: 404 not_found.
// Store unavailable: 503 listings_unavailable, not cached.
func DataListingsHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		if !isDirectorySite(config) {
			writeListingsJSON(w, http.StatusNotFound, listingsErrorJSON{Error: "not_found"})
			return
		}
		settings := directorySettingsFrom(config)
		id := httprouter.ParamsFromContext(req.Context()).ByName("id")
		switch id {
		case "search":
			serveListingsSearchJSON(w, req, settings)
		case "states":
			serveListingStatesJSON(w, req)
		case "cities":
			serveListingCitiesJSON(w, req)
		default:
			serveListingJSON(w, req, settings, id)
		}
	})
}

func serveListingsSearchJSON(w http.ResponseWriter, req *http.Request, settings directorySettings) {
	params := req.URL.Query()
	keyword := strings.Join(strings.Fields(params.Get("s")), " ")
	loc := resolveSearchLocation(req.Context(), params.Get("loc"), settings)
	page := listingsPageParam(params.Get("page"))
	// A smaller page than the site's, e.g. 1 when only the location is needed.
	pageSize := settings.PageSize
	if n, err := strconv.Atoi(params.Get("pageSize")); err == nil && n >= 1 && n < pageSize {
		pageSize = n
	}

	category, isCategory := settings.categoryNamed(keyword)
	q := settings.listingQuery(keyword, category, isCategory, loc)
	q.Page, q.PageSize = page, pageSize
	result, err := listingsStore.Search(req.Context(), q)
	if err != nil {
		listingsFailed("search", err)
		writeListingsUnavailable(w)
		return
	}
	if result.CityName != "" {
		loc.City = result.CityName
	}
	w.Header().Set("Cache-Control", listingsCacheControl)
	writeListingsJSON(w, http.StatusOK, listingSearchJSON{
		Keyword:    keyword,
		Category:   category.Slug,
		Location:   listingLocationJSON{City: loc.City, State: loc.State, Label: loc.Label(), Path: loc.Path()},
		Listings:   result.Listings,
		Total:      result.Total,
		Page:       result.Page,
		PageSize:   result.PageSize,
		TotalPages: result.TotalPages,
	})
}

// stateJSON is a state's code, name and page path.
func stateJSON(code string, count int) listingStateJSON {
	return listingStateJSON{Code: strings.ToUpper(code), Name: places.StateName(code), Path: "/" + strings.ToLower(code), Count: count}
}

func serveListingStatesJSON(w http.ResponseWriter, req *http.Request) {
	states, err := listingsStore.States(req.Context())
	if err != nil {
		listingsFailed("states", err)
		writeListingsUnavailable(w)
		return
	}
	out := listingStatesJSON{States: make([]listingStateJSON, 0, len(states))}
	for _, s := range states {
		out.States = append(out.States, stateJSON(s.Code, s.Count))
	}
	w.Header().Set("Cache-Control", listingsCacheControl)
	writeListingsJSON(w, http.StatusOK, out)
}

func serveListingCitiesJSON(w http.ResponseWriter, req *http.Request) {
	state := strings.TrimSpace(req.URL.Query().Get("state"))
	if !listings.IsStateCode(state) {
		writeListingsNotFound(w)
		return
	}
	cities, err := listingsStore.Cities(req.Context(), state)
	if err != nil {
		listingsFailed("cities "+state, err)
		writeListingsUnavailable(w)
		return
	}
	if len(cities) == 0 {
		writeListingsNotFound(w)
		return
	}
	w.Header().Set("Cache-Control", listingsCacheControl)
	out := listingCitiesJSON{State: stateJSON(state, 0), Cities: make([]listingCityJSON, 0, len(cities))}
	for _, c := range cities {
		loc := listings.Location{City: c.Name, State: c.State}
		out.Cities = append(out.Cities, listingCityJSON{Name: c.Name, Slug: c.Slug, Path: loc.Path(), Count: c.Count})
	}
	writeListingsJSON(w, http.StatusOK, out)
}

func serveListingJSON(w http.ResponseWriter, req *http.Request, settings directorySettings, id string) {
	if !listings.IsListingID(id) {
		writeListingsNotFound(w)
		return
	}
	l, found, err := listingsStore.Get(req.Context(), id)
	if err != nil {
		listingsFailed("get "+id, err)
		writeListingsUnavailable(w)
		return
	}
	if !found {
		writeListingsNotFound(w)
		return
	}
	nearby := []listings.Listing{}
	if settings.NearbyCount > 0 {
		if found, err := listingsStore.Nearby(req.Context(), l, "", settings.NearbyCount); err != nil {
			listingsFailed("nearby "+id, err)
		} else {
			nearby = found
		}
	}
	w.Header().Set("Cache-Control", listingsCacheControl)
	writeListingsJSON(w, http.StatusOK, listingDetailJSON{Listing: l, Nearby: nearby})
}

// writeListingsNotFound writes the API's 404 for an unknown id or state,
// cached like its answers.
func writeListingsNotFound(w http.ResponseWriter) {
	w.Header().Set("Cache-Control", listingsCacheControl)
	writeListingsJSON(w, http.StatusNotFound, listingsErrorJSON{Error: "not_found"})
}

func writeListingsUnavailable(w http.ResponseWriter) {
	w.Header().Set("Cache-Control", "no-store")
	writeListingsJSON(w, http.StatusServiceUnavailable, listingsErrorJSON{Error: "listings_unavailable"})
}

func writeListingsJSON(w http.ResponseWriter, status int, v interface{}) {
	out, err := json.Marshal(v)
	if err != nil {
		log.Printf("[ERROR] listings API: encoding: %v", err)
		http.Error(w, "failed to encode listings", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	w.Write(out)
}
