package handlers

import (
	"fmt"
	"net/http"
	"strconv"

	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/julienschmidt/httprouter"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleIssueGet godoc
// @Summary Search issue by ID
// @Description Returns all Issue related to the issue id
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id path int true "Issue ID"
// @Success 200 {object} common.JSONDBQueryResult{data=common.Issue}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /issue/{id} [get]
func HandleIssueGet(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())

	id, err := strconv.Atoi(params.ByName("id"))
	if err != nil {
		err = fmt.Errorf("invalid id")
	}
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusNotFound) {
		return
	}

	issue, err := services.GetDB().GetIssues().SelectByID(id)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
		Data: issue,
	})
}
