package system

import (
	"context"
	"kra/internal/biz/system"
	"testing"

	platformmodule "kra/pkg/module"
)

func TestSeedSystemCreatesInitialDataAndModuleSurface(t *testing.T) {
	db, err := openWithDriver("sqlite", "file:"+t.Name()+"?mode=memory&cache=shared")
	if err != nil {
		t.Fatal(err)
	}
	if err = migrateAll(db); err != nil {
		t.Fatal(err)
	}
	surface := platformmodule.Surface{
		Menus: []platformmodule.Menu{{Name: "orders", Path: "orders", ParentName: "extensions", Component: "view/orders.vue", Title: "订单", Sort: 6}},
		APIs:  []platformmodule.API{{Path: "/orders", Method: "GET", Group: "订单", Description: "订单列表"}},
	}
	input := &system.DatabaseConfig{AdminPassword: "admin-password", APIs: []*system.API{{Path: "/healthz", Method: "GET", APIGroup: "系统"}}}
	if err = SeedSystem(context.Background(), db, input, surface); err != nil {
		t.Fatal(err)
	}
	var admin userPO
	if err = db.Where("username = ?", "admin").First(&admin).Error; err != nil {
		t.Fatal(err)
	}
	var menu menuPO
	if err = db.Where("name = ?", "orders").First(&menu).Error; err != nil {
		t.Fatal(err)
	}
	var parent menuPO
	if err = db.Where("name = ?", "extensions").First(&parent).Error; err != nil {
		t.Fatal(err)
	}
	if menu.ParentID != parent.ID {
		t.Fatalf("module menu parent = %d, want %d", menu.ParentID, parent.ID)
	}
	var links int64
	if err = db.Model(&authorityMenuPO{}).Where("sys_authority_authority_id = ? AND sys_base_menu_id = ?", 888, menu.ID).Count(&links).Error; err != nil {
		t.Fatal(err)
	}
	if links != 1 {
		t.Fatalf("root menu links = %d, want 1", links)
	}
	var policies int64
	if err = policyScope(db).Where("v0 = ? AND v1 = ? AND v2 = ?", "888", "/orders", "GET").Count(&policies).Error; err != nil {
		t.Fatal(err)
	}
	if policies != 1 {
		t.Fatalf("root policies = %d, want 1", policies)
	}
}
