// Package listings serves the business listings of the directory sites
// (localpages, cured, customercompany, qualifiedlawyers) behind one Store
// interface. Until a DB-backed store exists, JSONLStore serves an export of
// the legacy business DB, one record per line.
package listings

import (
	"context"
	"errors"
	"log"
)

// ErrUnavailable is returned by every call to a store that has no listings
// (no import configured, or it failed to load).
var ErrUnavailable = errors.New("listings: store unavailable")

// Store is where the directory pages and the /data/listings API read listings.
type Store interface {
	// Search returns one page of the listings in q.Location (or within
	// q.RadiusMiles of it) matching q.Keyword and q.AnyOf/q.Group.
	Search(ctx context.Context, q Query) (Result, error)
	// Exists reports whether q's search finds any listing (its page ignored),
	// stopping at the first.
	Exists(ctx context.Context, q Query) (bool, error)
	// Get returns the listing with this id; ok is false when there is none.
	Get(ctx context.Context, id string) (Listing, bool, error)
	// Nearby returns up to n other listings in l's city that share one of its
	// categories (or match keyword).
	Nearby(ctx context.Context, l Listing, keyword string, n int) ([]Listing, error)
	// Cities returns the cities with listings in a state (code in any case),
	// A to Z by name; none for an unknown state.
	Cities(ctx context.Context, state string) ([]CityCount, error)
	// States returns the states with listings, A to Z by code.
	States(ctx context.Context) ([]StateCount, error)
	// ResolveLocation reads a location as the sites' search boxes and links
	// send it: "City, ST", "ST, City", "ST,City/", "City ST", a 5-digit zip
	// or a bare city, matched against the cities with listings. ok is false
	// when nothing matches.
	ResolveLocation(ctx context.Context, input string) (Location, bool, error)
	// Available reports whether the store has listings to serve.
	Available() bool
}

// Listing is one business, as the data API returns it. email is never exposed.
type Listing struct {
	ID             string        `json:"id"`
	Name           string        `json:"name"`
	URL            string        `json:"url"`
	Address        string        `json:"address"`
	City           string        `json:"city"`
	State          string        `json:"state"`
	Zip            string        `json:"zip"`
	Lat            *float64      `json:"lat"`
	Lon            *float64      `json:"lon"`
	Phones         []Phone       `json:"phones"`
	Website        string        `json:"website"`
	Categories     []string      `json:"categories"`
	Description    string        `json:"description"` // plain text, paragraphs separated by "\n"
	Hours          []string      `json:"hours"`       // one line per day, e.g. "Monday : 8:00 AM - 5:00 PM"
	Services       string        `json:"services"`
	Products       string        `json:"products"`
	PaymentOptions []string      `json:"paymentOptions"`
	SpecialOffer   *SpecialOffer `json:"specialOffer"`
	Images         []string      `json:"images"`
	Videos         []string      `json:"videos"` // YouTube video ids
	YextID         string        `json:"yextId"` // the record's Yext id, "" for other feeds (for the Yext pixels)
	// Source is the feed the record came from: "yext", "localeze", "ll",
	// "localpages" (a verified listing, from the API) or "".
	Source string `json:"source"`
	// Group is the record's category group, "" when it has none (matched by
	// Query.Group; not in the API).
	Group string `json:"-"`
}

// Phone is a listing phone number, Number formatted "(AAA) BBB-CCCC" and
// Tel the E.164 form for tel: links.
type Phone struct {
	Number string `json:"number"`
	Tel    string `json:"tel"`
	Label  string `json:"label"`
}

// SpecialOffer is a listing's offer text and link.
type SpecialOffer struct {
	Text string `json:"text"`
	URL  string `json:"url"`
}

// Query is a listings search: every listing in Location whose name or
// categories contain all the words of Keyword (an empty Keyword matches all).
// AnyOf and Group narrow it to a category group: a listing is in the group
// when every word of any one AnyOf term starts a word of its name or
// categories ("Pet Sitting" is in "Pet & Animal Sitting", "Arts" is not in
// "Auto Parts"), or its record's group equals Group (any case). A store keeps
// each group's membership once worked out, so AnyOf and Group come from the
// sites' configs, never from a request.
//
// RadiusMiles > 0 searches the listings within that distance of the city's
// centre, nearest first; 0 searches the exact city.
type Query struct {
	Keyword     string
	AnyOf       []string
	Group       string
	Location    Location
	RadiusMiles float64
	Page        int // 1-based; values below 1 read as 1
	PageSize    int // values below 1 read as DefaultPageSize
}

// CityCount is a city with listings: Slug is its CitySlug, State the
// upper-case state code, Count its number of listings.
type CityCount struct {
	Name  string
	Slug  string
	State string
	Count int
}

// StateCount is a state with listings: Code upper-case, Count its number of
// listings.
type StateCount struct {
	Code  string
	Count int
}

// DefaultPageSize is the page size of a Query that sets none.
const DefaultPageSize = 10

// MaxPageSize caps a Query's page size.
const MaxPageSize = 50

// Result is one page of a search.
type Result struct {
	Listings   []Listing
	Total      int
	Page       int
	PageSize   int
	TotalPages int
	// CityName is the location's city as the listings spell it ("Los Angeles"
	// for a "los-angeles" query), or "" when no listing is in that city.
	CityName string
}

// Disabled is the store used when no listings are configured: it is never
// available and every call returns ErrUnavailable.
type Disabled struct{}

func (Disabled) Search(context.Context, Query) (Result, error) { return Result{}, ErrUnavailable }
func (Disabled) Exists(context.Context, Query) (bool, error)   { return false, ErrUnavailable }
func (Disabled) Get(context.Context, string) (Listing, bool, error) {
	return Listing{}, false, ErrUnavailable
}
func (Disabled) Nearby(context.Context, Listing, string, int) ([]Listing, error) {
	return nil, ErrUnavailable
}
func (Disabled) Cities(context.Context, string) ([]CityCount, error) { return nil, ErrUnavailable }
func (Disabled) States(context.Context) ([]StateCount, error)        { return nil, ErrUnavailable }
func (Disabled) ResolveLocation(context.Context, string) (Location, bool, error) {
	return Location{}, false, ErrUnavailable
}
func (Disabled) Available() bool { return false }

// NewStore returns the store for a listings import: Disabled when jsonlPath is
// empty, else the JSONLStore loaded from it. A file that fails to load is
// logged and gives Disabled, so a bad import never stops the service.
func NewStore(jsonlPath string) Store {
	if jsonlPath == "" {
		log.Printf("[INFO] listings: no listings_jsonl_path, directory listings disabled")
		return Disabled{}
	}
	store, err := LoadJSONL(jsonlPath)
	if err != nil {
		log.Printf("[ERROR] listings: loading %s: %v; directory listings disabled", jsonlPath, err)
		return Disabled{}
	}
	return store
}
