package system

import (
	"testing"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	systemModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemRes "github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
	"github.com/gin-gonic/gin"
	"github.com/glebarez/sqlite"
	"github.com/stretchr/testify/require"
	"gorm.io/gorm"
)

func setupApiServiceTestDB(t *testing.T) {
	t.Helper()

	db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
	require.NoError(t, err)
	require.NoError(t, db.AutoMigrate(&systemModel.SysApi{}, &systemModel.SysIgnoreApi{}))

	global.GVA_DB = db
	global.GVA_ROUTERS = gin.RoutesInfo{
		{
			Method: "POST",
			Path:   "/book/createBook",
		},
	}

	t.Cleanup(func() {
		global.GVA_DB = nil
		global.GVA_ROUTERS = nil
	})
}

func TestApiService_EnterSyncApiSyncsRoutesWhenPayloadIsEmpty(t *testing.T) {
	setupApiServiceTestDB(t)

	err := ApiServiceApp.EnterSyncApi(systemRes.SysSyncApis{})
	require.NoError(t, err)

	var api systemModel.SysApi
	err = global.GVA_DB.Where("path = ? AND method = ?", "/book/createBook", "POST").First(&api).Error
	require.NoError(t, err)
	require.Equal(t, "/book/createBook", api.Path)
	require.Equal(t, "POST", api.Method)
}

func TestApiService_EnterSyncApiKeepsExistingApiMetadata(t *testing.T) {
	setupApiServiceTestDB(t)
	err := global.GVA_DB.Create(&systemModel.SysApi{
		Path:        "/book/createBook",
		Method:      "POST",
		ApiGroup:    "book-admin",
		Description: "创建书籍",
	}).Error
	require.NoError(t, err)

	err = ApiServiceApp.EnterSyncApi(systemRes.SysSyncApis{})
	require.NoError(t, err)

	var api systemModel.SysApi
	err = global.GVA_DB.Where("path = ? AND method = ?", "/book/createBook", "POST").First(&api).Error
	require.NoError(t, err)
	require.Equal(t, "book-admin", api.ApiGroup)
	require.Equal(t, "创建书籍", api.Description)
}

func TestApiService_EnterSyncApiSkipsIgnoredRoutes(t *testing.T) {
	setupApiServiceTestDB(t)
	err := global.GVA_DB.Create(&systemModel.SysIgnoreApi{
		Path:   "/book/createBook",
		Method: "POST",
	}).Error
	require.NoError(t, err)

	err = ApiServiceApp.EnterSyncApi(systemRes.SysSyncApis{})
	require.NoError(t, err)

	var count int64
	err = global.GVA_DB.Model(&systemModel.SysApi{}).Where("path = ? AND method = ?", "/book/createBook", "POST").Count(&count).Error
	require.NoError(t, err)
	require.Zero(t, count)
}
