package siteimp

import (
	"context"
	"encoding/json"
	"net/http"

	api "github.com/tech/sendico/pkg/api/http"
	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/messaging"
	snotifications "github.com/tech/sendico/pkg/messaging/notifications/site"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	eapi "github.com/tech/sendico/server/interface/api"
	"go.uber.org/zap"
)

type SiteAPI struct {
	logger   mlogger.Logger
	producer messaging.Producer
}

func (a *SiteAPI) Name() mservice.Type {
	return mservice.Site
}

func (a *SiteAPI) Finish(_ context.Context) error {
	return nil
}

func (a *SiteAPI) demoRequest(r *http.Request) http.HandlerFunc {
	var request model.DemoRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		a.logger.Warn("Failed to decode demo request payload", zap.Error(err))
		return response.BadRequest(a.logger, a.Name(), "invalid_payload", "Failed to decode demo request payload")
	}
	request.Normalize()
	if err := request.Validate(); err != nil {
		a.logger.Warn("Demo request validation failed", zap.Error(err))
		return response.BadPayload(a.logger, a.Name(), err)
	}

	if err := a.producer.SendMessage(snotifications.DemoRequest(a.Name(), &request)); err != nil {
		a.logger.Warn("Failed to enqueue demo request notification", zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}

	return response.Accepted(a.logger, map[string]string{"status": "queued"})
}

func CreateAPI(a eapi.API) (*SiteAPI, error) {
	p := &SiteAPI{
		logger:   a.Logger().Named(mservice.Site),
		producer: a.Register().Messaging().Producer(),
	}

	a.Register().Handler(mservice.Site, "/demo/request", api.Post, p.demoRequest)
	return p, nil
}
