// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/me/changeemail_request.go
package me

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"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_me "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/service/me"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
)

type PostChangeEmailRequestHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	service    svc_me.ChangeEmailRequestService
	middleware middleware.Middleware
}

func NewPostChangeEmailRequestHTTPHandler(
	config *config.Configuration,
	logger *zap.Logger,
	service svc_me.ChangeEmailRequestService,
	middleware middleware.Middleware,
) *PostChangeEmailRequestHTTPHandler {
	logger = logger.With(zap.String("module", "maplefile"))
	logger = logger.Named("PostChangeEmailRequestHTTPHandler")
	return &PostChangeEmailRequestHTTPHandler{
		config:     config,
		logger:     logger,
		service:    service,
		middleware: middleware,
	}
}

func (*PostChangeEmailRequestHTTPHandler) Pattern() string {
	return "POST /api/v1/me/email/change-request"
}

func (r *PostChangeEmailRequestHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Apply middleware before handling the request
	r.middleware.Attach(r.Execute)(w, req)
}

func (h *PostChangeEmailRequestHTTPHandler) unmarshalRequest(
	ctx context.Context,
	r *http.Request,
) (*svc_me.ChangeEmailRequestDTO, error) {
	var requestData svc_me.ChangeEmailRequestDTO

	defer r.Body.Close()

	var rawJSON bytes.Buffer
	teeReader := io.TeeReader(r.Body, &rawJSON) // TeeReader allows you to read the JSON and capture it

	err := json.NewDecoder(teeReader).Decode(&requestData)
	if err != nil {
		h.logger.Error("decoding error",
			zap.Any("err", err),
			zap.String("json", rawJSON.String()),
		)
		return nil, httperror.NewForSingleField(http.StatusBadRequest, "non_field_error", "payload structure is wrong")
	}

	return &requestData, nil
}

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

	ctx := r.Context()

	req, err := h.unmarshalRequest(ctx, r)
	if err != nil {
		httperror.RespondWithError(w, r, err)
		return
	}

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

	// Encode response
	if resp != nil {
		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
		}
	} else {
		err := errors.New("no result")
		httperror.RespondWithError(w, r, err)
		return
	}
}
