package handlers

import (
	"net/http"
	"net/url"
	"otaupdate/services"
	"time"

	"github.com/pkg/errors"

	"github.com/fiskerinc/cloud-services/pkg/common"
	orm "github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleAPICallsGet godoc
// @Summary Search API calls
// @Description Get API calls filtered by method, user, path and date.
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param search query string false "Text search"
// @Param from query string false "Date before requests which client is looking for"
// @Param to query string false "Date after requests which client is looking for"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Param order query string false "Sort on column with asc or desc"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.APICall}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /apicalls [get]
func HandleAPICallsGet(w http.ResponseWriter, r *http.Request) {
	filter, err := parseAPICallsFilter(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	options, err := orm.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}
	if options.Order == "" {
		options.Order = "created_at DESC"
	}

	csDB := services.GetDB().GetAPICalls()
	cs, total, err := csDB.Search(filter, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
		Data:  cs,
		Total: total,
	})
}

func parseAPICallsFilter(r *http.Request) (common.APICallsSearch, error) {
	qs := r.URL.Query()
	from, err := parseTimeFilter(qs, "from")
	if err != nil {
		return common.APICallsSearch{}, err
	}

	to, err := parseTimeFilter(qs, "to")
	if err != nil {
		return common.APICallsSearch{}, err
	}

	return common.APICallsSearch{
		Search: qs.Get("search"),
		From:   from,
		To:     to,
	}, nil
}

func parseTimeFilter(qs url.Values, pname string) (*time.Time, error) {
	stime := qs.Get(pname)
	if stime == "" {
		return nil, nil
	}

	t, err := time.Parse(time.RFC3339, stime)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return &t, nil
}
