//go:build integration

package lifecycle

import (
	"context"
	"slices"
	"testing"

	"github.com/tidbcloud/controlplane9/internal/config"
	"github.com/tidbcloud/controlplane9/internal/host"
	cptilt "github.com/tidbcloud/controlplane9/internal/tilt"
)

func TestIntegration_SessionReadyWaitsForMetaDBBeforeSeedingIdentity(t *testing.T) {
	stateDir := t.TempDir()
	if err := host.Save(stateDir, &host.Session{
		Mode: config.HostModeRemoteEC2K3d,
		Remote: &host.RemoteSession{
			PublicHTTPSURL: "https://cp9-session-ready.cp9.dev.aws.tidbcloud.com",
		},
	}); err != nil {
		t.Fatal(err)
	}
	events := make([]string, 0, 3)
	step := &SessionReadyStep{
		StateDir: stateDir,
		Session: &config.SessionConfig{
			Host: config.SessionHostConfig{Mode: config.HostModeRemoteEC2K3d},
			Tilt: config.SessionTiltConfig{File: "personas/dev-full/runtime/example.Tiltfile"},
			UI: config.SessionUIConfig{
				SeedIdentity: config.SessionUISeedIdentityConfig{Email: "user@example.com"},
			},
			EssentialV2: &config.SessionEssentialV2Config{Enabled: true},
		},
		TiltResourceReadiness: func(context.Context, string, int) (*cptilt.ResourceReadiness, error) {
			events = append(events, "tilt")
			return &cptilt.ResourceReadiness{
				ReadyResources:    1,
				TotalResources:    2,
				NotReadyResources: []string{"dbaas-ui"},
				ResourceReady: map[string]bool{
					"premium-metadb": true,
					"dbaas-ui":       false,
				},
				ResourceStates: map[string]cptilt.ResourceState{
					"dbaas-ui": {UpdateStatus: "error", Message: "frontend failed"},
				},
			}, nil
		},
		KubectlRunner: func(
			_ context.Context,
			_ *host.Session,
			_ []byte,
			args ...string,
		) ([]byte, error) {
			if slices.Contains(args, "deployment/premium-metadb") {
				events = append(events, "metadb-rollout")
				return nil, nil
			}
			if slices.Contains(args, "deploy/premium-metadb") {
				events = append(events, "seed")
				return []byte("1"), nil
			}
			return nil, nil
		},
	}

	if err := step.runRemoteUIReadiness(context.Background(), &cptilt.Status{Mode: "up"}); err == nil {
		t.Fatal("runRemoteUIReadiness succeeded with failed dbaas-ui")
	}
	want := []string{"tilt", "metadb-rollout", "seed", "tilt"}
	if !slices.Equal(events, want) {
		t.Fatalf("events = %v, want %v", events, want)
	}
}
