package app

import (
	"context"
	"net/http/httptest"
	"testing"

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

func TestResumePendingBatchImportRunsCompletesStoredRun(t *testing.T) {
	t.Parallel()

	server := httptest.NewServer(newBatchImportActionStubServer(t))
	defer server.Close()

	dsn := testutil.SQLiteTestDSN(t, "state.db", true)
	store := testutil.OpenSQLiteStore(t, dsn)
	defer closeAppTestStore(t, store)
	if _, err := store.SQLDB().Exec("PRAGMA foreign_keys = OFF"); err != nil {
		t.Fatalf("disable foreign keys pragma error = %v", err)
	}

	hostPK, err := store.Hosts().Create(context.Background(), sqlite.Host{
		HostID:              "host-1",
		BaseURL:             server.URL,
		HostVersion:         "0.1.126",
		CapabilityProbeJSON: "{}",
		AuthType:            "apikey",
		AuthToken:           "host-token",
	})
	if err != nil {
		t.Fatalf("Hosts().Create() error = %v", err)
	}

	if err := store.ImportRuns().Create(context.Background(), sqlite.ImportRun{
		RunID:                 "run-resume-1",
		HostID:                "host-1",
		Mode:                  "strict",
		AccessMode:            "self_service",
		SubscriptionUsersJSON: `[]`,
		SubscriptionDays:      0,
		ProbeAPIKey:           "gateway-key",
		State:                 "running",
		TotalItems:            1,
	}); err != nil {
		t.Fatalf("ImportRuns().Create() error = %v", err)
	}

	legacyBatchID := int64(81)
	if err := store.ImportRunItems().Upsert(context.Background(), sqlite.ImportRunItem{
		ItemID:                "item-resume-1",
		RunID:                 "run-resume-1",
		BaseURL:               server.URL,
		ProviderID:            "provider-resume-1",
		APIKeyFingerprint:     "sha256:test",
		RequestedModelsJSON:   `["kimi-k2.6"]`,
		RawModelsJSON:         `["kimi-k2.6"]`,
		NormalizedModelsJSON:  `["kimi-k2.6"]`,
		CanonicalFamiliesJSON: `["kimi-2.6"]`,
		RecommendedModelsJSON: `["kimi-k2.6"]`,
		ResolvedSmokeModel:    "kimi-k2.6",
		CapabilityProfileJSON: `{"transport_profile":{"supports_openai_chat_completions":true}}`,
		CurrentStage:          "confirm",
		ConfirmationStatus:    "pending",
		AccessStatus:          "unknown",
		MatchedAccountState:   "none",
		AccountResolution:     "created",
		LegacyBatchID:         &legacyBatchID,
	}); err != nil {
		t.Fatalf("ImportRunItems().Upsert() error = %v", err)
	}

	if _, err := store.ManagedResources().Create(context.Background(), sqlite.ManagedResource{
		BatchID:        legacyBatchID,
		HostID:         hostPK,
		ResourceType:   "account",
		HostResourceID: "account_1",
		ResourceName:   "batch-import-account",
	}); err != nil {
		t.Fatalf("ManagedResources().Create(account) error = %v", err)
	}

	if err := resumePendingBatchImportRuns(context.Background(), dsn); err != nil {
		t.Fatalf("resumePendingBatchImportRuns() error = %v", err)
	}

	run, err := store.ImportRuns().GetByRunID(context.Background(), "run-resume-1")
	if err != nil {
		t.Fatalf("ImportRuns().GetByRunID() error = %v", err)
	}
	if run.State != "completed" {
		t.Fatalf("run.State = %q, want completed", run.State)
	}
	if run.CompletedItems != 1 || run.ActiveItems != 1 {
		t.Fatalf("run counters = %+v, want completed_items=1 active_items=1", run)
	}

	item, err := store.ImportRunItems().GetByItemID(context.Background(), "item-resume-1")
	if err != nil {
		t.Fatalf("ImportRunItems().GetByItemID() error = %v", err)
	}
	if item.CurrentStage != "done" || item.ConfirmationStatus != "confirmed" || item.AccessStatus != "active" {
		t.Fatalf("item = %+v, want done/confirmed/active", item)
	}
}
