package handlers

import (
	"context"
	"errors"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/orchard9/rdev/pkg/api"
)

// MergeFeatureRequest is the request body for merging a feature.
type MergeFeatureRequest struct {
	Strategy string `json:"strategy,omitempty"`
}

// MergeFeature merges a feature branch after all gates pass.
// POST /projects/{id}/sdlc/features/{slug}/merge
func (h *SDLCHandler) MergeFeature(w http.ResponseWriter, r *http.Request) {
	projectID := chi.URLParam(r, "id")
	slug := chi.URLParam(r, "slug")

	var req MergeFeatureRequest
	if err := api.DecodeJSON(r, &req); err != nil && !errors.Is(err, api.ErrEmptyBody) {
		api.WriteBadRequest(w, r, "invalid request body")
		return
	}

	strategy := req.Strategy
	if strategy == "" {
		strategy = "squash"
	}

	ctx, cancel := context.WithTimeout(r.Context(), TimeoutHeavyWrite)
	defer cancel()

	if err := h.sdlcService.MergeFeature(ctx, projectID, slug, strategy); err != nil {
		writeSDLCError(w, r, err)
		return
	}

	api.WriteSuccess(w, r, map[string]string{"status": "merged", "strategy": strategy})
}

// ArchiveFeature archives a released feature.
// POST /projects/{id}/sdlc/features/{slug}/archive
func (h *SDLCHandler) ArchiveFeature(w http.ResponseWriter, r *http.Request) {
	projectID := chi.URLParam(r, "id")
	slug := chi.URLParam(r, "slug")

	ctx, cancel := context.WithTimeout(r.Context(), TimeoutStandard)
	defer cancel()

	if err := h.sdlcService.ArchiveFeature(ctx, projectID, slug); err != nil {
		writeSDLCError(w, r, err)
		return
	}

	api.WriteSuccess(w, r, map[string]string{"status": "archived"})
}
