/*
 * Solidarity Mobility API
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * API version: 1.0.0
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
 */

package openapi

import (
	"net/http"
	"strings"
)

// SearchAPIController binds http requests to an api service and writes the service results to the http response
type SearchAPIController struct {
	service      SearchAPIServicer
	errorHandler ErrorHandler
}

// SearchAPIOption for how the controller is set up.
type SearchAPIOption func(*SearchAPIController)

// WithSearchAPIErrorHandler inject ErrorHandler into controller
func WithSearchAPIErrorHandler(h ErrorHandler) SearchAPIOption {
	return func(c *SearchAPIController) {
		c.errorHandler = h
	}
}

// NewSearchAPIController creates a default api controller
func NewSearchAPIController(s SearchAPIServicer, opts ...SearchAPIOption) Router {
	controller := &SearchAPIController{
		service:      s,
		errorHandler: DefaultErrorHandler,
	}

	for _, opt := range opts {
		opt(controller)
	}

	return controller
}

// Routes returns all the api routes for the SearchAPIController
func (c *SearchAPIController) Routes() Routes {
	return Routes{
		"GetDriverJourneys": Route{
			strings.ToUpper("Get"),
			"/driver_journeys",
			c.GetDriverJourneys,
		},
	}
}

// GetDriverJourneys - Search for matching punctual planned outward driver journeys.
func (c *SearchAPIController) GetDriverJourneys(w http.ResponseWriter, r *http.Request) {
	authenticated := CheckOperatorAuthorization(r, AuthorizedOperators)
	if !authenticated {
		response := ImplResponse{
			Code: 401,
			Body: "Unauthorized request. Check your operator / API Key.",
		}
		EncodeJSONResponse(response.Body, &response.Code, w)
		return
	}
	query := r.URL.Query()
	departureLatParam, err := parseNumericParameter[float32](
		query.Get("departureLat"),
		WithRequire[float32](parseFloat32),
	)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	departureLngParam, err := parseNumericParameter[float32](
		query.Get("departureLng"),
		WithRequire[float32](parseFloat32),
	)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	departureDateParam, err := parseNumericParameter[int32](
		query.Get("departureDate"),
		WithRequire[int32](parseInt32),
	)
	if err != nil {
		c.errorHandler(w, r, &ParsingError{Err: err}, nil)
		return
	}
	operatorParam := query.Get("operator")
	result, err := c.service.GetDriverJourneys(r.Context(), departureLatParam, departureLngParam, departureDateParam, operatorParam)
	// If an error occurred, encode the error with the status code
	if err != nil {
		c.errorHandler(w, r, err, &result)
		return
	}
	// If no error, encode the body and the result code
	EncodeJSONResponse(result.Body, &result.Code, w)
}
