package integration_test

import (
	"context"
	"testing"

	"sub2api-cn-relay-manager/internal/store/sqlite"
)

func TestStoreRuntimeCreatesOperationalTables(t *testing.T) {
	store := openTestStore(t)
	defer closeTestStore(t, store)

	for _, table := range []string{
		"hosts",
		"packs",
		"providers",
		"import_batches",
		"import_batch_items",
		"managed_resources",
		"probe_results",
		"access_closure_records",
		"reconcile_runs",
	} {
		if !tableExists(t, store.SQLDB(), table) {
			t.Fatalf("table %q does not exist after store initialization", table)
		}
	}
}

func TestStoreRuntimePersistsOperationalRecords(t *testing.T) {
	ctx := context.Background()
	store := openTestStore(t)
	defer closeTestStore(t, store)

	hostID, err := store.Hosts().Create(ctx, sqlite.Host{
		HostID:              "host-1",
		BaseURL:             "https://sub2api.example.com",
		HostVersion:         "0.1.126",
		CapabilityProbeJSON: `{"supports_batch_accounts":true}`,
	})
	if err != nil {
		t.Fatalf("Hosts().Create() error = %v", err)
	}

	packID, err := store.Packs().Create(ctx, sqlite.Pack{
		PackID:   "openai-cn-pack",
		Version:  "1.0.0",
		Checksum: "checksum-1",
	})
	if err != nil {
		t.Fatalf("Packs().Create() error = %v", err)
	}

	providerID, err := store.Providers().Create(ctx, sqlite.Provider{
		PackID:      packID,
		ProviderID:  "deepseek",
		DisplayName: "DeepSeek",
		BaseURL:     "https://api.deepseek.com",
		Platform:    "openai",
	})
	if err != nil {
		t.Fatalf("Providers().Create() error = %v", err)
	}

	batchID, err := store.ImportBatches().Create(ctx, sqlite.ImportBatch{
		HostID:       hostID,
		PackID:       packID,
		ProviderID:   providerID,
		Mode:         "strict",
		BatchStatus:  "running",
		AccessStatus: "not_configured",
	})
	if err != nil {
		t.Fatalf("ImportBatches().Create() error = %v", err)
	}

	itemID, err := store.ImportBatchItems().Create(ctx, sqlite.ImportBatchItem{
		BatchID:          batchID,
		KeyFingerprint:   "fp-1",
		AccountStatus:    "pending",
		ProbeSummaryJSON: `{}`,
	})
	if err != nil {
		t.Fatalf("ImportBatchItems().Create() error = %v", err)
	}

	if _, err := store.ManagedResources().Create(ctx, sqlite.ManagedResource{
		BatchID:        batchID,
		HostID:         hostID,
		ResourceType:   "group",
		HostResourceID: "group-1",
		ResourceName:   "deepseek-group",
	}); err != nil {
		t.Fatalf("ManagedResources().Create() error = %v", err)
	}

	if _, err := store.ProbeResults().Create(ctx, sqlite.ProbeResult{
		BatchItemID: itemID,
		ProbeType:   "models",
		Status:      "passed",
		SummaryJSON: `{"models":["deepseek-chat"]}`,
	}); err != nil {
		t.Fatalf("ProbeResults().Create() error = %v", err)
	}

	if _, err := store.AccessClosures().Create(ctx, sqlite.AccessClosureRecord{
		BatchID:     batchID,
		ClosureType: "subscription",
		Status:      "subscription_ready",
		DetailsJSON: `{"api_key_bound":true}`,
	}); err != nil {
		t.Fatalf("AccessClosures().Create() error = %v", err)
	}

	if _, err := store.ReconcileRuns().Create(ctx, sqlite.ReconcileRun{
		BatchID:     batchID,
		HostID:      hostID,
		ProviderID:  providerID,
		Status:      "drifted",
		SummaryJSON: `{"missing_resources":1}`,
	}); err != nil {
		t.Fatalf("ReconcileRuns().Create() error = %v", err)
	}

	if got := countRows(t, store.SQLDB(), "import_batches"); got != 1 {
		t.Fatalf("import_batches row count = %d, want 1", got)
	}
	if got := countRows(t, store.SQLDB(), "import_batch_items"); got != 1 {
		t.Fatalf("import_batch_items row count = %d, want 1", got)
	}
	if got := countRows(t, store.SQLDB(), "managed_resources"); got != 1 {
		t.Fatalf("managed_resources row count = %d, want 1", got)
	}
	if got := countRows(t, store.SQLDB(), "probe_results"); got != 1 {
		t.Fatalf("probe_results row count = %d, want 1", got)
	}
	if got := countRows(t, store.SQLDB(), "access_closure_records"); got != 1 {
		t.Fatalf("access_closure_records row count = %d, want 1", got)
	}
	if got := countRows(t, store.SQLDB(), "reconcile_runs"); got != 1 {
		t.Fatalf("reconcile_runs row count = %d, want 1", got)
	}
}
