package blueprint

import "testing"

func TestMergeIntoAddsPages(t *testing.T) {
	base := &Blueprint{
		Version: "1.0",
		Meta:    Meta{Name: "app", Slug: "demo"},
		Entities: []Entity{{
			Name: "item", Table: "item", Label: "Item", PrimaryKey: "id",
			Fields: []Field{{Name: "id", Label: "ID", Type: "string"}},
		}},
		Apis: Apis{
			BasePath: "/api/v1/apps/demo",
			Resources: []APIResource{{
				Entity: "item", Path: "/items", Operations: []string{"list"},
			}},
		},
		Pages: []Page{{ID: "item_list", Title: "列表", Route: "/items", Type: "list", Entity: "item"}},
	}
	incoming := &Blueprint{
		Entities: []Entity{{
			Name: "order", Table: "order", Label: "Order", PrimaryKey: "id",
			Fields: []Field{{Name: "id", Label: "ID", Type: "string"}},
		}},
		Apis: Apis{Resources: []APIResource{{
			Entity: "order", Path: "/orders", Operations: []string{"list", "import"},
		}}},
		Pages: []Page{{ID: "order_list", Title: "订单", Route: "/orders", Type: "list", Entity: "order"}},
	}
	res, err := MergeInto(base, incoming)
	if err != nil {
		t.Fatal(err)
	}
	if len(res.AddedPages) != 1 || res.AddedPages[0] != "order_list" {
		t.Fatalf("added pages: %+v", res.AddedPages)
	}
	if len(base.Pages) != 2 || len(base.Entities) != 2 {
		t.Fatalf("pages=%d entities=%d", len(base.Pages), len(base.Entities))
	}
}

func TestMergeIntoRejectsDuplicatePageID(t *testing.T) {
	base := &Blueprint{
		Pages: []Page{{ID: "a", Route: "/a", Type: "list", Entity: "x"}},
	}
	incoming := &Blueprint{
		Pages: []Page{{ID: "a", Route: "/b", Type: "list", Entity: "x"}},
	}
	if _, err := MergeInto(base, incoming); err == nil {
		t.Fatal("expected duplicate page id error")
	}
}
