// pkg/bdd/steps/<feature>_steps.go
package steps

import (
	"DanceLessonsCoach/pkg/bdd/testserver"
	"fmt"
	"strings"

	"github.com/cucumber/godog"
)

// StepContext holds the test client and implements all step definitions
type StepContext struct {
	client *testserver.Client
}

// NewStepContext creates a new step context
func NewStepContext(client *testserver.Client) *StepContext {
	return &StepContext{client: client}
}

// InitializeSteps registers step definitions for the feature
func InitializeSteps(ctx *godog.ScenarioContext, client *testserver.Client) {
	sc := NewStepContext(client)

	// Use Godog's EXACT regex patterns and parameter names
	ctx.Step(`^I request a greeting for "([^"]*)"$`, sc.iRequestAGreetingFor)
	ctx.Step(`^I request the default greeting$`, sc.iRequestTheDefaultGreeting)
	ctx.Step(`^I request the health endpoint$`, sc.iRequestTheHealthEndpoint)
	ctx.Step(`^the response should be "{\"([^"]*)\":\"([^"]*)"}"$`, sc.theResponseShouldBe)
	ctx.Step(`^the server is running$`, sc.theServerIsRunning)
}

func (sc *StepContext) iRequestAGreetingFor(name string) error {
	return sc.client.Request("GET", fmt.Sprintf("/api/v1/greet/%s", name), nil)
}

func (sc *StepContext) iRequestTheDefaultGreeting() error {
	return sc.client.Request("GET", "/api/v1/greet/", nil)
}

func (sc *StepContext) iRequestTheHealthEndpoint() error {
	return sc.client.Request("GET", "/api/health", nil)
}

func (sc *StepContext) theResponseShouldBe(arg1, arg2 string) error {
	// The regex captures the full JSON from the feature file, including quotes
	// We need to extract just the key and value without the surrounding quotes and backslashes

	// Remove the surrounding quotes and backslashes
	cleanArg1 := strings.Trim(arg1, `"\`)
	cleanArg2 := strings.Trim(arg2, `"\`)

	// Build the expected JSON string
	expected := fmt.Sprintf(`{"%s":"%s"}`, cleanArg1, cleanArg2)

	return sc.client.ExpectResponseBody(expected)
}

func (sc *StepContext) theServerIsRunning() error {
	// Actually verify the server is running by checking the readiness endpoint
	return sc.client.Request("GET", "/api/ready", nil)
}
