package routes

import (
	"context"
	"encoding/json"
	"log"
	"net/http"
	"strings"
	"sync"
	"time"

	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/spf13/viper"
)

// A shop site's /deals page lists the products of shared.shop.pages.deals.skus
// (brandzones: live's fixed list of 200), all on one page, hiding the SKUs
// the shop API no longer has. Looking 200 SKUs up per visit is too slow, so
// each SKU's answer is kept for shopDealsTTL and refreshed in the background
// (see StartShopDealsWarmer); /data/shop/deals answers from what is known.
const (
	// shopDealsTTL is how long a SKU's product, or its being gone (404), is kept.
	shopDealsTTL = 6 * time.Hour
	// shopDealsRetryAfter is the wait before a SKU whose lookup failed (not a
	// 404) is looked up again.
	shopDealsRetryAfter = 5 * time.Minute
	// shopDealsWorkers caps concurrent product lookups of one refresh.
	shopDealsWorkers = 6
	// shopDealsWarmInterval is how often the warmer refreshes what expired.
	shopDealsWarmInterval = 10 * time.Minute
)

// shopDeal is what is known of one SKU's product.
type shopDeal struct {
	Product json.RawMessage // data.product_details; nil when gone or not known
	Gone    bool            // the shop API answered 404
	Failed  bool            // the last lookup failed (timeout, 5xx, 400...)
	At      time.Time       // when the last lookup ended
}

// due reports whether the SKU needs a lookup at now.
func (d shopDeal) due(now time.Time) bool {
	if d.At.IsZero() {
		return true
	}
	if d.Failed {
		return now.Sub(d.At) >= shopDealsRetryAfter
	}
	return now.Sub(d.At) >= shopDealsTTL
}

// shopDealsStore holds the deals lookups, by affiliate and SKU.
type shopDealsStore struct {
	mu         sync.Mutex
	deals      map[string]shopDeal
	refreshing map[string]bool // by affiliate: a refresh is running
}

var shopDeals = &shopDealsStore{deals: map[string]shopDeal{}, refreshing: map[string]bool{}}

func shopDealKey(affiliate, sku string) string {
	return affiliate + " " + sku
}

// shopDealsSettings returns the site's deals SKUs (in config order, without
// blanks or repeats) and affiliate; ok is false when the site has no deals page.
func shopDealsSettings(config *middlewares.ClientConfig) (skus []string, affiliate string, ok bool) {
	if !isShopSite(config) {
		return nil, "", false
	}
	pages, _ := shopBlock(config)["pages"].(map[string]interface{})
	deals, ok := pages[shopDealsPage].(map[string]interface{})
	if !ok {
		return nil, "", false
	}
	list, _ := deals["skus"].([]interface{})
	seen := map[string]bool{}
	for _, item := range list {
		if sku, _ := item.(string); strings.TrimSpace(sku) != "" && !seen[strings.TrimSpace(sku)] {
			seen[strings.TrimSpace(sku)] = true
			skus = append(skus, strings.TrimSpace(sku))
		}
	}
	return skus, shopAffiliateFromConfig(config), true
}

// snapshot returns the site's known products in SKU order, and whether the
// list is partial: some SKU not looked up yet, or whose last lookup failed
// with nothing known before (gone SKUs don't count). due lists the SKUs
// needing a lookup.
func (s *shopDealsStore) snapshot(affiliate string, skus []string, now time.Time) (products []json.RawMessage, partial bool, due []string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, sku := range skus {
		d := s.deals[shopDealKey(affiliate, sku)]
		if d.due(now) {
			due = append(due, sku)
		}
		switch {
		case d.Product != nil:
			products = append(products, d.Product)
		case !d.Gone:
			partial = true
		}
	}
	return products, partial, due
}

// refresh looks up the due SKUs, shopDealsWorkers at a time, unless a refresh
// for the affiliate is already running. A 404 marks the SKU gone; another
// failure keeps a product already known (marked for a retry) and never
// marks it gone. Blocks until done.
func (s *shopDealsStore) refresh(ctx context.Context, affiliate string, skus []string) {
	s.mu.Lock()
	if s.refreshing[affiliate] {
		s.mu.Unlock()
		return
	}
	s.refreshing[affiliate] = true
	s.mu.Unlock()
	defer func() {
		s.mu.Lock()
		delete(s.refreshing, affiliate)
		s.mu.Unlock()
	}()

	_, _, due := s.snapshot(affiliate, skus, time.Now())
	forEachConcurrently(due, shopDealsWorkers, func(sku string) {
		product, err := fetchShopDealProduct(ctx, sku, affiliate)
		key := shopDealKey(affiliate, sku)
		s.mu.Lock()
		defer s.mu.Unlock()
		switch {
		case err == errShopProductMissing:
			s.deals[key] = shopDeal{Gone: true, At: time.Now()}
		case err != nil:
			log.Printf("[WARN] shop deals: %s: %v", sku, err)
			d := s.deals[key]
			d.Failed, d.At = true, time.Now()
			s.deals[key] = d
		default:
			s.deals[key] = shopDeal{Product: product, At: time.Now()}
		}
	})
}

// fetchShopDealProduct is a product's data.product_details as the shop API
// gives it (errShopProductMissing for a 404).
func fetchShopDealProduct(ctx context.Context, sku, affiliate string) (json.RawMessage, error) {
	ctx, cancel := context.WithTimeout(ctx, shopUpstreamTimeout)
	defer cancel()
	status, body, err := shopGet(ctx, shopProductURL(sku, affiliate))
	if err != nil {
		return nil, err
	}
	if status == http.StatusNotFound {
		return nil, errShopProductMissing
	}
	if status != http.StatusOK {
		return nil, &shopStatusError{status}
	}
	var response struct {
		Data struct {
			Product json.RawMessage `json:"product_details"`
		} `json:"data"`
	}
	if err := json.Unmarshal(body, &response); err != nil {
		return nil, err
	}
	if len(response.Data.Product) == 0 || string(response.Data.Product) == "null" {
		return nil, &shopStatusError{status}
	}
	return response.Data.Product, nil
}

// shopStatusError is a shop API answer without a product.
type shopStatusError struct{ status int }

func (e *shopStatusError) Error() string {
	return "upstream returned " + http.StatusText(e.status)
}

// shopDealsResponse is /data/shop/deals' answer.
type shopDealsResponse struct {
	Success bool              `json:"success"`
	Partial bool              `json:"partial"`
	Data    []json.RawMessage `json:"data"`
}

// DataShopDealsHandler serves GET /data/shop/deals on a shop site with a
// deals page: {"success": true, "partial": bool, "data": [product_details...]},
// every known live product of shared.shop.pages.deals.skus in config order
// (the shop API's product_details objects, as /data/shop/product/:sku gives
// them under data.product_details). Gone SKUs (404) are left out. partial is
// true while some SKU isn't known yet (cold start) or failed with nothing
// known before; the frontend may ask again later. Due SKUs are refreshed in
// the background, so the answer never waits for the shop API. Other sites:
// 404 {"success": false, "data": []}.
func DataShopDealsHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		skus, affiliate, ok := shopDealsSettings(middlewares.GetClientConfig(req.Context()))
		if !ok {
			w.WriteHeader(http.StatusNotFound)
			json.NewEncoder(w).Encode(shopDealsResponse{Data: []json.RawMessage{}})
			return
		}
		products, partial, due := shopDeals.snapshot(affiliate, skus, time.Now())
		if len(due) > 0 {
			go shopDeals.refresh(context.Background(), affiliate, skus)
		}
		if products == nil {
			products = []json.RawMessage{}
		}
		if partial {
			w.Header().Set("Cache-Control", "no-store")
		} else {
			w.Header().Set("Cache-Control", "public, max-age=300")
		}
		json.NewEncoder(w).Encode(shopDealsResponse{Success: true, Partial: partial, Data: products})
	})
}

// StartShopDealsWarmer looks up every shop site's deals SKUs in the
// background at startup, then every shopDealsWarmInterval refreshes those
// expired or failed, so /deals visitors never wait for cold lookups. Like
// the CMS warmer it runs only with "cms_warm" set (uat, prod); without it
// the first /data/shop/deals request starts the lookups (partial until
// done). Reports whether it started. Must run after ClientConfigMiddleware
// has loaded the site list.
func StartShopDealsWarmer() bool {
	if !viper.GetBool("cms_warm") {
		return false
	}
	go func() {
		for {
			for _, config := range middlewares.AllClientConfigs() {
				if skus, affiliate, ok := shopDealsSettings(config); ok && len(skus) > 0 {
					func() {
						defer logWarmPanic("shop deals " + affiliate)
						shopDeals.refresh(context.Background(), affiliate, skus)
					}()
				}
			}
			time.Sleep(shopDealsWarmInterval)
		}
	}()
	return true
}
