// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/blockedemail/list.go
package blockedemail

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

	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/middleware"
	svc_blockedemail "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/service/blockedemail"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
)

type ListBlockedEmailsHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	service    svc_blockedemail.ListBlockedEmailsService
	middleware middleware.Middleware
}

func NewListBlockedEmailsHTTPHandler(
	config *config.Configuration,
	logger *zap.Logger,
	service svc_blockedemail.ListBlockedEmailsService,
	middleware middleware.Middleware,
) *ListBlockedEmailsHTTPHandler {
	logger = logger.Named("ListBlockedEmailsHTTPHandler")
	return &ListBlockedEmailsHTTPHandler{
		config:     config,
		logger:     logger,
		service:    service,
		middleware: middleware,
	}
}

func (*ListBlockedEmailsHTTPHandler) Pattern() string {
	return "GET /api/v1/me/blocked-emails"
}

func (h *ListBlockedEmailsHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	h.middleware.Attach(h.Execute)(w, req)
}

func (h *ListBlockedEmailsHTTPHandler) Execute(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	ctx := r.Context()

	resp, err := h.service.Execute(ctx)
	if err != nil {
		httperror.RespondWithError(w, r, err)
		return
	}

	if err := json.NewEncoder(w).Encode(resp); err != nil {
		h.logger.Error("failed to encode response",
			zap.Any("error", err))
		httperror.RespondWithError(w, r, err)
		return
	}
}
