package scenarios_test

// Scenario tests for Lead Convert functionality.
//
// LEAD-001: Verify the Lead Convert endpoint exists and is functional.

import (
	"fmt"
	"net/http"
	"testing"
	"time"

	"github.com/nexuscrm/tests/contract/internal/liveapi"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestLEAD001_ConvertEndpointExists(t *testing.T) {
	// Scenario: The Lead Convert feature is required for the standard
	// sales workflow (Lead → Convert → Account/Contact/Opportunity).
	// PDF confirmed this is completely missing.
	//
	// This test verifies whether the convert endpoint exists at all.

	// Bootstrap: ensure Lead object and fields exist
	if !ensureLead(t) {
		t.Fatal("could not bootstrap Lead object")
	}

	client := liveapi.NewAuthenticatedClient(t)

	// Create a test Lead (include Name since it's a required system field)
	leadResp, err := client.DoJSON(http.MethodPost, "/sobjects/Lead", map[string]any{
		"Name":     fmt.Sprintf("ConvertTest_%d", time.Now().UnixNano()),
		"LastName": fmt.Sprintf("ConvertTest_%d", time.Now().UnixNano()),
		"Company":  "Test Corp",
	})
	require.NoError(t, err)

	if leadResp.StatusCode != http.StatusCreated {
		body := liveapi.ReadBody(t, leadResp)
		t.Fatalf("could not create test Lead (status %d): %s", leadResp.StatusCode, string(body))
	}

	var leadBody struct{ ID string `json:"id"` }
	liveapi.DecodeJSON(t, leadResp, &leadBody)
	require.NotEmpty(t, leadBody.ID)

	t.Cleanup(func() {
		delResp, _ := client.Do(http.MethodDelete, "/sobjects/Lead/"+leadBody.ID, "", nil)
		if delResp != nil {
			delResp.Body.Close()
		}
	})

	// Try to convert the Lead
	// Salesforce uses POST /actions/standard/convertLead
	convertResp, err := client.DoJSON(http.MethodPost,
		"/actions/standard/convertLead",
		map[string]any{
			"inputs": []map[string]any{{
				"leadId":          leadBody.ID,
				"convertedStatus": "Closed - Converted",
			}},
		})
	require.NoError(t, err)

	body := liveapi.ReadBody(t, convertResp)

	// If 404: endpoint doesn't exist (the PDF issue — feature missing)
	// If 200/201: feature exists and works
	if convertResp.StatusCode == http.StatusNotFound {
		t.Fatalf("FINDING: Lead Convert endpoint not implemented (404). "+
			"This is a confirmed missing feature from the PDF. Response: %s", string(body))
	}

	assert.True(t, convertResp.StatusCode == http.StatusOK || convertResp.StatusCode == http.StatusCreated,
		"Lead Convert should return 200 or 201, got %d: %s", convertResp.StatusCode, string(body))
}
