package handlers

import (
	"context"
	"net/http"

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

// CreateBranch creates a feature branch.
// POST /projects/{id}/sdlc/features/{slug}/branches
func (h *SDLCHandler) CreateBranch(w http.ResponseWriter, r *http.Request) {
	projectID := chi.URLParam(r, "id")
	slug := chi.URLParam(r, "slug")

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

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

	api.WriteCreated(w, r, manifest)
}

// GetBranchStatus returns the branch manifest for a feature.
// GET /projects/{id}/sdlc/features/{slug}/branches
func (h *SDLCHandler) GetBranchStatus(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()

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

	api.WriteSuccess(w, r, manifest)
}

// SyncBranch syncs a feature branch with its base branch.
// POST /projects/{id}/sdlc/features/{slug}/branches/sync
func (h *SDLCHandler) SyncBranch(w http.ResponseWriter, r *http.Request) {
	projectID := chi.URLParam(r, "id")
	slug := chi.URLParam(r, "slug")

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

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

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