// discussion_endpoint.go defines the /discussion endpoint behavior.
// Layer: adapters/inbound/httpapi discussion route.
package httpapi

import (
	"context"
	"time"

	"gitea.maximumdirect.net/ejr/feedapi/endpoint"
	"gitea.maximumdirect.net/ejr/feedapi/render"
	"gitea.maximumdirect.net/ejr/feedapi/response"
	"gitea.maximumdirect.net/ejr/weatherapi/internal/adapters/inbound/httpapi/presenter"
	"gitea.maximumdirect.net/ejr/weatherfeeder/model"
)

func discussionDefinitions(svc Service) []endpoint.Definition {
	return []endpoint.Definition{
		discussionDefinition(
			"/discussion",
			"discussion.txt.tmpl",
			func(run *model.WeatherForecastDiscussion, units presenter.Units, tz *time.Location) any {
				return presenter.DiscussionPayload(run, units, tz)
			},
			svc,
		),
		discussionDefinition(
			"/discussion/key-messages",
			"discussion_key_messages.txt.tmpl",
			func(run *model.WeatherForecastDiscussion, units presenter.Units, tz *time.Location) any {
				return presenter.DiscussionKeyMessagesOnlyPayload(run, units, tz)
			},
			svc,
		),
		discussionDefinition(
			"/discussion/short-term",
			"discussion_short_term.txt.tmpl",
			func(run *model.WeatherForecastDiscussion, units presenter.Units, tz *time.Location) any {
				return presenter.DiscussionShortTermOnlyPayload(run, units, tz)
			},
			svc,
		),
		discussionDefinition(
			"/discussion/long-term",
			"discussion_long_term.txt.tmpl",
			func(run *model.WeatherForecastDiscussion, units presenter.Units, tz *time.Location) any {
				return presenter.DiscussionLongTermOnlyPayload(run, units, tz)
			},
			svc,
		),
	}
}

func discussionDefinition(
	path string,
	templateName string,
	present func(*model.WeatherForecastDiscussion, presenter.Units, *time.Location) any,
	svc Service,
) endpoint.Definition {
	return endpoint.GET(
		path,
		bindTimezoneQuery,
		func(ctx context.Context, req timezoneQueryRequest) (any, error) {
			run, err := svc.LatestForecastDiscussion(ctx)
			if err != nil {
				return nil, err
			}
			return response.Envelope{Data: present(run, req.Units, req.Timezone)}, nil
		},
		endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
		endpoint.WithTemplate(templateName),
	)
}
