package members_client

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	"code.tnxs.net/vernonkeenan/lib/api/members/members_client/track_events"
	"code.tnxs.net/vernonkeenan/lib/api/members/members_models"
	"github.com/go-openapi/strfmt"
)

func TestTrackEventClientExposesOnlyReadAndImmutableCreate(t *testing.T) {
	client := track_events.New(nil, strfmt.Default)
	if client == nil {
		t.Fatal("generated TrackEvent client is nil")
	}
	var _ track_events.ClientService = client

	params := track_events.NewGetTrackEventsParams().
		WithID(trackEventString("association")).
		WithTrackID(trackEventString("track")).
		WithEventID(trackEventString("event"))
	if params.ID == nil || *params.ID != "association" ||
		params.TrackID == nil || *params.TrackID != "track" ||
		params.EventID == nil || *params.EventID != "event" {
		t.Fatal("generated TrackEvent GET filters do not preserve values")
	}

	request := &members_models.TrackEventRequest{Data: []*members_models.TrackEvent{{
		EventID: "event", TrackID: "track",
	}}}
	create := track_events.NewPostTrackEventsParams().WithTrackEventRequest(request)
	if create.TrackEventRequest != request {
		t.Fatal("generated TrackEvent POST does not preserve its request")
	}

	entries, err := os.ReadDir("track_events")
	if err != nil {
		t.Fatal(err)
	}
	for _, entry := range entries {
		name := strings.ToLower(entry.Name())
		if strings.Contains(name, "put_") || strings.Contains(name, "delete_") {
			t.Errorf("forbidden mutable TrackEvent operation artifact: %s", name)
		}
	}
}

func TestTrackEventClientHasNoLegacyOrCredentialSurface(t *testing.T) {
	for _, root := range []string{"track_events", "../members_models"} {
		err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if info.IsDir() || (!strings.Contains(path, "track_event") && root != "track_events") {
				return nil
			}
			raw, readErr := os.ReadFile(path)
			if readErr != nil {
				return readErr
			}
			source := strings.ToLower(string(raw))
			forbidden := []string{"salesforce", "sf-gate", "go-force", "cache"}
			if root != "track_events" {
				forbidden = append(forbidden, "api_key", "credential", "password", "token")
			}
			for _, forbidden := range forbidden {
				if strings.Contains(source, forbidden) {
					t.Errorf("%s contains forbidden coupling %q", path, forbidden)
				}
			}
			return nil
		})
		if err != nil {
			t.Fatal(err)
		}
	}
}

func trackEventString(value string) *string { return &value }
