package handlers

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/orchard9/rdev/internal/sdlc"
)

func TestSDLCHandler_MergeFeature(t *testing.T) {
	exec := &testSDLCExecutor{}
	_, router := setupSDLCHandler(exec)

	req := httptest.NewRequest(http.MethodPost, "/projects/test-project/sdlc/features/auth-flow/merge", nil)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d: %s", w.Code, w.Body.String())
	}
}

func TestSDLCHandler_MergeFeature_WithStrategy(t *testing.T) {
	exec := &testSDLCExecutor{}
	_, router := setupSDLCHandler(exec)

	body, _ := json.Marshal(MergeFeatureRequest{Strategy: "merge"})
	req := httptest.NewRequest(http.MethodPost, "/projects/test-project/sdlc/features/auth-flow/merge", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d: %s", w.Code, w.Body.String())
	}
}

func TestSDLCHandler_MergeFeature_NotReady(t *testing.T) {
	exec := &testSDLCExecutor{err: sdlc.ErrMergeNotReady}
	_, router := setupSDLCHandler(exec)

	req := httptest.NewRequest(http.MethodPost, "/projects/test-project/sdlc/features/auth-flow/merge", nil)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	if w.Code != http.StatusBadRequest {
		t.Errorf("expected status 400, got %d: %s", w.Code, w.Body.String())
	}
}

func TestSDLCHandler_MergeFeature_FeatureNotFound(t *testing.T) {
	exec := &testSDLCExecutor{err: sdlc.ErrFeatureNotFound}
	_, router := setupSDLCHandler(exec)

	req := httptest.NewRequest(http.MethodPost, "/projects/test-project/sdlc/features/nonexistent/merge", nil)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	if w.Code != http.StatusNotFound {
		t.Errorf("expected status 404, got %d: %s", w.Code, w.Body.String())
	}
}

func TestSDLCHandler_ArchiveFeature(t *testing.T) {
	exec := &testSDLCExecutor{}
	_, router := setupSDLCHandler(exec)

	req := httptest.NewRequest(http.MethodPost, "/projects/test-project/sdlc/features/auth-flow/archive", nil)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	if w.Code != http.StatusOK {
		t.Errorf("expected status 200, got %d: %s", w.Code, w.Body.String())
	}
}

func TestSDLCHandler_ArchiveFeature_NotFound(t *testing.T) {
	exec := &testSDLCExecutor{err: sdlc.ErrFeatureNotFound}
	_, router := setupSDLCHandler(exec)

	req := httptest.NewRequest(http.MethodPost, "/projects/test-project/sdlc/features/nonexistent/archive", nil)
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	if w.Code != http.StatusNotFound {
		t.Errorf("expected status 404, got %d: %s", w.Code, w.Body.String())
	}
}
