package system

import (
	"context"
	"strings"
	"time"

	"kra/internal/biz"
	platformmodule "kra/pkg/module"

	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func SeedSystem(ctx context.Context, db *gorm.DB, input *biz.DatabaseConfig, surfaces ...platformmodule.Surface) error {
	return seedSystem(ctx, db, input, nil, surfaces...)
}

// SeedSystemWithCatalog applies module-contributed administration surfaces and
// default timed tasks in one transaction. The system module remains the owner
// of the system tables, while other modules contribute through the catalog.
func SeedSystemWithCatalog(ctx context.Context, db *gorm.DB, input *biz.DatabaseConfig, catalog platformmodule.Catalog) error {
	surfaces := make([]platformmodule.Surface, 0, len(catalog.Definitions))
	for _, definition := range catalog.Definitions {
		surfaces = append(surfaces, definition.Surface)
	}
	return seedSystem(ctx, db, input, catalog.DefaultTimedTasks(), surfaces...)
}

func seedSystem(ctx context.Context, db *gorm.DB, input *biz.DatabaseConfig, defaults []platformmodule.TimedTask, surfaces ...platformmodule.Surface) error {
	return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		rootParentID := uint(0)
		authority := authorityPO{AuthorityID: 888, AuthorityName: "超级管理员", ParentID: &rootParentID, DataScope: 1, DefaultRouter: "dashboard"}
		if err := tx.FirstOrCreate(&authority, authorityPO{AuthorityID: 888}).Error; err != nil {
			return err
		}
		if err := tx.Model(&authorityPO{}).Where("authority_id = ? AND parent_id IS NULL", 888).Update("parent_id", 0).Error; err != nil {
			return err
		}
		menus := defaultMenus()
		for i := range menus {
			if err := tx.Where("name = ?", menus[i].Name).FirstOrCreate(&menus[i]).Error; err != nil {
				return err
			}
		}
		for _, surface := range surfaces {
			if err := seedAdminSurface(tx, surface); err != nil {
				return err
			}
		}
		var persisted []menuPO
		if err := tx.Order("sort asc, id asc").Find(&persisted).Error; err != nil {
			return err
		}
		nameID := make(map[string]uint, len(persisted))
		for _, menu := range persisted {
			nameID[menu.Name] = menu.ID
		}
		for i := range menus {
			if menus[i].ActiveName != "" {
				if err := tx.Model(&menuPO{}).Where("name = ?", menus[i].Name).Updates(map[string]any{"parent_id": nameID[menus[i].ActiveName], "active_name": ""}).Error; err != nil {
					return err
				}
			}
		}
		if err := tx.Where("sys_authority_authority_id = ?", 888).Delete(&authorityMenuPO{}).Error; err != nil {
			return err
		}
		links := make([]authorityMenuPO, 0, len(persisted))
		for _, menu := range persisted {
			links = append(links, authorityMenuPO{SysAuthorityAuthorityID: 888, SysBaseMenuID: menu.ID})
		}
		if len(links) > 0 {
			if err := tx.Create(&links).Error; err != nil {
				return err
			}
		}
		var count int64
		if err := tx.Model(&userPO{}).Where("username = ?", "admin").Count(&count).Error; err != nil {
			return err
		}
		if count == 0 {
			hash, err := bcrypt.GenerateFromPassword([]byte(input.AdminPassword), bcrypt.DefaultCost)
			if err != nil {
				return err
			}
			now := time.Now()
			user := userPO{UUID: uuid.NewString(), Username: "admin", Password: string(hash), NickName: "超级管理员", AuthorityID: 888, Enable: 1, PasswordUpdatedAt: &now}
			if err := tx.Create(&user).Error; err != nil {
				return err
			}
			if err := tx.Create(&userAuthorityPO{SysUserID: user.ID, SysAuthorityAuthorityID: 888}).Error; err != nil {
				return err
			}
		}
		enabled := true
		department := departmentPO{Name: "总公司", ParentID: 0, Ancestors: "0", Sort: 0, Status: &enabled}
		if err := tx.Where("name = ?", department.Name).FirstOrCreate(&department).Error; err != nil {
			return err
		}
		for _, position := range []positionPO{{Name: "总经理", Code: "CEO", Sort: 1, Status: &enabled}, {Name: "普通员工", Code: "STAFF", Sort: 2, Status: &enabled}} {
			if err := tx.Where("code = ?", position.Code).FirstOrCreate(&position).Error; err != nil {
				return err
			}
		}
		security := DefaultSecurityConfig()
		if err := tx.FirstOrCreate(&security, SecurityConfigPO{ID: 1}).Error; err != nil {
			return err
		}
		exportTemplate := exportTemplatePO{Name: "api", DBTableName: "sys_apis", TemplateID: "api", TemplateInfo: "{\n\"path\":\"路径\",\n\"method\":\"方法（大写）\",\n\"description\":\"方法介绍\",\n\"api_group\":\"方法分组\"\n}"}
		if err := tx.Where("template_id = ?", exportTemplate.TemplateID).FirstOrCreate(&exportTemplate).Error; err != nil {
			return err
		}
		var defaultTasks []taskPO
		if defaults == nil {
			defaultTasks = []taskPO{{Name: "ClearDB", Description: "定时清理数据库过期日志(操作记录/JWT黑名单/定时任务执行日志)", Spec: "@daily", ExecutorType: "method", MethodName: "ClearDB", Enabled: true}, {Name: "CleanStaleUploads", Description: "定时清理过期大文件上传会话", Spec: "@hourly", ExecutorType: "method", MethodName: "CleanStaleUploads", Enabled: true}}
		}
		for _, item := range defaults {
			defaultTasks = append(defaultTasks, taskPO{Name: item.Name, Description: item.Description, Spec: item.Spec, WithSeconds: item.WithSeconds, ExecutorType: "method", MethodName: item.MethodName, Enabled: item.Enabled})
		}
		for _, task := range defaultTasks {
			if err := tx.Where("name = ?", task.Name).FirstOrCreate(&task).Error; err != nil {
				return err
			}
		}
		for _, item := range input.APIs {
			if item != nil {
				po := apiPO{Path: item.Path, Method: strings.ToUpper(item.Method), Description: item.Description, APIGroup: item.APIGroup}
				if err := tx.Where("path = ? AND method = ?", po.Path, po.Method).FirstOrCreate(&po).Error; err != nil {
					return err
				}
			}
		}
		ignoredAPIs := make([]ignoredAPIPO, 0)
		for _, item := range DefaultIgnoredAPIs("uploads/file") {
			ignoredAPIs = append(ignoredAPIs, ignoredAPIPO{Method: item.Method, Path: item.Path})
		}
		for _, ignored := range ignoredAPIs {
			if err := tx.FirstOrCreate(&ignored, ignored).Error; err != nil {
				return err
			}
		}
		ignoreSet := make(map[string]struct{}, len(ignoredAPIs))
		for _, ignored := range ignoredAPIs {
			ignoreSet[ignored.Method+"\x00"+ignored.Path] = struct{}{}
		}
		var apiRows []apiPO
		if err := tx.Find(&apiRows).Error; err != nil {
			return err
		}
		for _, api := range apiRows {
			if _, ignored := ignoreSet[api.Method+"\x00"+api.Path]; ignored {
				continue
			}
			exists, err := policyExists(tx, 888, api.Path, api.Method)
			if err != nil {
				return err
			}
			if !exists {
				rule := newPolicyRule(888, api.Path, api.Method)
				if err := tx.Create(&rule).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})
}

func seedAdminSurface(tx *gorm.DB, surface platformmodule.Surface) error {
	for _, item := range surface.Menus {
		parentID := uint(0)
		if item.ParentName != "" {
			var parent menuPO
			if err := tx.Where("name = ?", item.ParentName).First(&parent).Error; err != nil {
				return err
			}
			parentID = parent.ID
		}
		menu := menuPO{
			MenuLevel: 1,
			ParentID:  parentID,
			Path:      item.Path,
			Name:      item.Name,
			Component: item.Component,
			Title:     item.Title,
			Icon:      item.Icon,
			Sort:      item.Sort,
		}
		if item.ParentName == "" {
			menu.MenuLevel = 0
		}
		if err := tx.Where("name = ?", item.Name).FirstOrCreate(&menu).Error; err != nil {
			return err
		}
	}
	for _, item := range surface.APIs {
		api := apiPO{
			Path:        item.Path,
			Method:      strings.ToUpper(item.Method),
			APIGroup:    item.Group,
			Description: item.Description,
		}
		if err := tx.Where("path = ? AND method = ?", api.Path, api.Method).FirstOrCreate(&api).Error; err != nil {
			return err
		}
	}
	return nil
}

func defaultMenus() []menuPO {
	root := func(path, name, title, icon string, sort int) menuPO {
		return menuPO{Path: path, Name: name, Component: "view/routerHolder.vue", Title: title, Icon: icon, Sort: sort}
	}
	child := func(parent, path, name, component, title, icon string, sort int) menuPO {
		return menuPO{MenuLevel: 1, Path: path, Name: name, Component: component, Title: title, Icon: icon, Sort: sort, ActiveName: parent}
	}
	cachedChild := func(parent, path, name, component, title, icon string, sort int) menuPO {
		value := child(parent, path, name, component, title, icon, sort)
		value.KeepAlive = true
		return value
	}
	return []menuPO{{Path: "dashboard", Name: "dashboard", Component: "view/dashboard/index.vue", Title: "仪表盘", Icon: "odometer", Sort: 1}, root("permission", "permission", "权限管理", "perm-kra", 2), root("org", "org", "组织管理", "share", 3), root("systemConfig", "systemConfig", "系统设置", "config-kra", 4), root("monitor", "monitor", "运维监控", "monitor-kra", 5), root("media", "media", "媒体管理", "folder-opened", 6), root("extensions", "extensions", "扩展功能", "cherry", 10), {Path: "person", Name: "person", Component: "view/person/person.vue", Title: "个人信息", Icon: "postcard", Hidden: true, Sort: 13}, child("permission", "authority", "authority", "view/superAdmin/authority/authority.vue", "角色管理", "role-kra", 1), cachedChild("permission", "menu", "menu", "view/superAdmin/menu/menu.vue", "菜单管理", "tickets", 2), cachedChild("permission", "api", "api", "view/superAdmin/api/api.vue", "api管理", "api-kra", 3), child("permission", "apiToken", "apiToken", "view/systemTools/apiToken/index.vue", "API Token", "key", 4), child("org", "user", "user", "view/superAdmin/user/user.vue", "用户管理", "user", 1), child("org", "department", "department", "view/superAdmin/department/department.vue", "部门管理", "office-building", 2), child("org", "position", "position", "view/superAdmin/position/position.vue", "岗位管理", "postcard", 3), child("systemConfig", "system", "system", "view/systemTools/system/system.vue", "配置文件", "config-file-kra", 1), child("systemConfig", "dictionary", "dictionary", "view/superAdmin/dictionary/sysDictionary.vue", "字典管理", "notebook", 2), child("systemConfig", "sysParams", "sysParams", "view/superAdmin/params/sysParams.vue", "参数管理", "set-up", 3), child("systemConfig", "security", "security", "view/system/security/index.vue", "安全配置", "security-kra", 4), child("monitor", "operation", "operation", "view/superAdmin/operation/sysOperationRecord.vue", "操作历史", "document", 1), child("monitor", "loginLog", "loginLog", "view/systemTools/loginLog/index.vue", "登录日志", "clock", 2), child("monitor", "sysError", "sysError", "view/systemTools/sysError/sysError.vue", "错误日志", "error-kra", 3), child("monitor", "sysVersion", "sysVersion", "view/systemTools/version/version.vue", "版本管理", "version-kra", 4), child("monitor", "state", "state", "view/system/state.vue", "服务器状态", "server", 5), child("monitor", "dataAccessLog", "dataAccessLog", "view/superAdmin/dataAccessLog/dataAccessLog.vue", "数据权限审计", "warning", 6), child("monitor", "timedTask", "timedTask", "view/systemTools/timedTask/index.vue", "定时任务", "timer", 7), child("monitor", "logViewer", "logViewer", "view/systemTools/logViewer/index.vue", "文件日志", "document", 8), child("media", "upload", "upload", "view/media/upload.vue", "媒体库（上传下载）", "upload", 1), child("media", "chunkUpload", "chunkUpload", "view/media/chunkUpload.vue", "大文件上传", "folder-add", 2), child("extensions", "email", "email", "modules/email/view/index.vue", "邮件发送", "message", 4), child("extensions", "anInfo", "anInfo", "modules/announcement/view/info.vue", "公告管理", "bell", 5)}
}
