package main

func generateHandlersHTTP() {
	generateToFile(headerHandlersHTTP, templateFuncHandlersHTTP, "internal/api/handler_gen.go", nil, nil)
}

var headerHandlersHTTP = `// Code generated by internal/gen/api/main.go. DO NOT EDIT.

package api

import (
	"io"
	"net/http"

	. "github.com/centrifugal/centrifugo/v6/internal/apiproto"

	"go.opentelemetry.io/otel/codes"
	"go.opentelemetry.io/otel/trace"
)
`

var templateFuncHandlersHTTP = `
func (s *Handler) handle{{ .RequestCapitalized }}(w http.ResponseWriter, r *http.Request) {
	data, err := io.ReadAll(r.Body)
	if err != nil {
		incErrorStringCode(s.api.config.Protocol, "{{ .RequestSnake }}", "read_body")
		s.handleReadDataError(r, w, err)
		return
	}

	req, err := requestDecoder.Decode{{ .RequestCapitalized }}(data)
	if err != nil {
		incErrorStringCode(s.api.config.Protocol, "{{ .RequestSnake }}", "unmarshal")
		s.handleUnmarshalError(r, w, err)
		return
	}

	resp := s.api.{{ .RequestCapitalized }}(r.Context(), req)

{{- if ne .RequestCapitalized "Batch" }}
	if s.config.UseOpenTelemetry && resp.Error != nil {
		span := trace.SpanFromContext(r.Context())
		span.SetStatus(codes.Error, resp.Error.Error())
	}

	if resp.Error != nil && s.useTransportErrorMode(r) {
		incError(s.api.config.Protocol, "{{ .RequestSnake }}", resp.Error.Code)
		statusCode := MapErrorToHTTPCode(resp.Error)
		data, _ = EncodeError(resp.Error)
		s.writeJsonCustomStatus(w, statusCode, data)
		return
	}
{{- end}}

	data, err = responseEncoder.Encode{{ .RequestCapitalized }}(resp)
	if err != nil {
		incErrorStringCode(s.api.config.Protocol, "{{ .RequestSnake }}", "marshal")
		s.handleMarshalError(r, w, err)
		return
	}

{{- if ne .RequestCapitalized "Batch" }}
	if resp.Error != nil {
		incError(s.api.config.Protocol, "{{ .RequestSnake }}", resp.Error.Code)
	}
{{- end}}

	s.writeJson(w, data)
}
`
