package meta

import (
	"context"
	"testing"

	"aijianzhan/platform/internal/blueprint"
)

func TestBackfillDefaultImportExport(t *testing.T) {
	store := NewMemoryStore()
	bp := &blueprint.Blueprint{}
	bp.Meta.Name = "coerce"
	bp.Meta.Slug = "coerce_fields"
	bp.Apis.Resources = []blueprint.APIResource{{
		Path:       "items",
		Entity:     "item",
		Operations: []string{"list", "get", "create", "update", "delete"},
	}}
	bp.Entities = []blueprint.Entity{{Name: "item", Table: "item", PrimaryKey: "id"}}
	bp.Pages = []blueprint.Page{{ID: "list1", Type: "list", Layout: &blueprint.PageLayout{Actions: []string{"create", "refresh"}}}}
	_ = store.Save(context.Background(), &AppRecord{
		AppID: "a1", TenantID: 1, Slug: "coerce_fields", Name: "coerce",
		Status: StatusPublished, Blueprint: bp,
	})

	dry, err := BackfillDefaultImportExport(context.Background(), store, true)
	if err != nil {
		t.Fatal(err)
	}
	if dry.Updated != 1 {
		t.Fatalf("dry updated=%d", dry.Updated)
	}
	app, _ := store.GetBySlug(context.Background(), 1, "coerce_fields")
	if hasImport(app.Blueprint.Apis.Resources[0].Operations) {
		t.Fatal("dry run should not persist")
	}

	res, err := BackfillDefaultImportExport(context.Background(), store, false)
	if err != nil {
		t.Fatal(err)
	}
	if res.Updated != 1 {
		t.Fatalf("updated=%d", res.Updated)
	}
	app, _ = store.GetBySlug(context.Background(), 1, "coerce_fields")
	if !hasImport(app.Blueprint.Apis.Resources[0].Operations) {
		t.Fatalf("ops=%v", app.Blueprint.Apis.Resources[0].Operations)
	}
}

func hasImport(ops []string) bool {
	for _, op := range ops {
		if op == "import" {
			return true
		}
	}
	return false
}
