package blueprint_test

import (
	"encoding/json"
	"testing"

	"aijianzhan/platform/internal/blueprint"
)

func TestEnsureDefaultImportExport(t *testing.T) {
	bp := &blueprint.Blueprint{
		Apis: blueprint.Apis{
			Resources: []blueprint.APIResource{
				{Entity: "a", Path: "/a", Operations: []string{"list", "get", "create", "update", "delete"}},
				{Entity: "ro", Path: "/ro", Operations: []string{"list", "get"}},
				{Entity: "b", Path: "/b", Operations: []string{"list", "create", "import"}},
			},
		},
		Pages: []blueprint.Page{
			{ID: "p1", Type: "list", Entity: "a", Layout: &blueprint.PageLayout{Actions: []string{"create", "edit", "delete", "refresh"}}},
			{ID: "p2", Type: "form", Entity: "a"},
		},
	}
	bp.EnsureDefaultImportExport()

	ops0 := bp.Apis.Resources[0].Operations
	if !contains(ops0, "import") || !contains(ops0, "export") {
		t.Fatalf("writable resource should get import/export, got %v", ops0)
	}
	opsRO := bp.Apis.Resources[1].Operations
	if contains(opsRO, "import") {
		t.Fatalf("read-only should not get import, got %v", opsRO)
	}
	opsB := bp.Apis.Resources[2].Operations
	if !contains(opsB, "export") || countOp(opsB, "import") != 1 {
		t.Fatalf("should add export once, keep import: %v", opsB)
	}
	acts := bp.Pages[0].Layout.Actions
	if !contains(acts, "import") || !contains(acts, "export") {
		t.Fatalf("list actions should include import/export: %v", acts)
	}
}

func TestEnsureDefaultImportExportDisabled(t *testing.T) {
	ui, _ := json.Marshal(map[string]any{"disable_default_import": true})
	bp := &blueprint.Blueprint{
		Meta: blueprint.Meta{UI: ui},
		Apis: blueprint.Apis{
			Resources: []blueprint.APIResource{
				{Entity: "a", Path: "/a", Operations: []string{"list", "create"}},
			},
		},
	}
	bp.EnsureDefaultImportExport()
	if contains(bp.Apis.Resources[0].Operations, "import") {
		t.Fatal("disable_default_import should skip")
	}
}

func contains(ss []string, want string) bool {
	for _, s := range ss {
		if s == want {
			return true
		}
	}
	return false
}

func countOp(ss []string, want string) int {
	n := 0
	for _, s := range ss {
		if s == want {
			n++
		}
	}
	return n
}
