package ws

import "testing"

// TestRepoStatusFromInit covers the NS-03 status projection: success,
// the "already initialised" idempotency cases (treated as success),
// and arbitrary failures (preserved into the host row's error field).
func TestRepoStatusFromInit(t *testing.T) {
	t.Parallel()
	cases := []struct {
		name      string
		jobStatus string
		errMsg    string
		want      string
		wantErr   string
	}{
		{"succeeded", "succeeded", "", "ready", ""},
		{"already initialised (en-GB)", "failed", "Fatal: create repository at rest:http://r failed: server response unexpected: config file already exists", "ready", ""},
		{"already initialised (en-US spelling)", "failed", "boom: already init" + "ialized", "ready", ""},
		{"bad creds", "failed", "Fatal: server response unexpected: 401 Unauthorised", "init_failed", "Fatal: server response unexpected: 401 Unauthorised"},
		{"network", "failed", "dial tcp 192.168.0.99:8000: i/o timeout", "init_failed", "dial tcp 192.168.0.99:8000: i/o timeout"},
	}
	for _, c := range cases {
		c := c
		t.Run(c.name, func(t *testing.T) {
			t.Parallel()
			gotStatus, gotErr := repoStatusFromInit(c.jobStatus, c.errMsg)
			if gotStatus != c.want {
				t.Errorf("status: got %q, want %q", gotStatus, c.want)
			}
			if gotErr != c.wantErr {
				t.Errorf("err: got %q, want %q", gotErr, c.wantErr)
			}
		})
	}
}

// TestRepoStatusFromInitTruncates: huge stack traces from the agent
// should not bloat the hosts row. Cap at 512 + ellipsis.
func TestRepoStatusFromInitTruncates(t *testing.T) {
	t.Parallel()
	long := make([]byte, 1024)
	for i := range long {
		long[i] = 'x'
	}
	_, got := repoStatusFromInit("failed", string(long))
	if len(got) > 520 {
		t.Errorf("err length: got %d, want <= 520 (512 + ellipsis runes)", len(got))
	}
}
