package repository

import "hyapp-admin-server/internal/model"

const (
	roleCodePlatformAdmin        = "platform-admin"
	roleCodeOperationsLead       = "ops-admin"
	roleCodeOperationsSpecialist = "operations-specialist"
	roleCodeProductLead          = "product-lead"
	roleCodeProductSpecialist    = "product-specialist"
	roleCodeFinanceLead          = "finance-lead"
	roleCodeFinanceSpecialist    = "finance-specialist"
)

// managedDefaultRoles 对应产品确认的七类固定岗位。platform-admin 与 ops-admin 保留历史 code，
// 避免存量用户关联、财务全量数据范围判断以及已执行迁移中的角色引用失效；展示名称按新岗位体系收敛。
var managedDefaultRoles = []model.Role{
	{Name: "超级管理员", Code: roleCodePlatformAdmin, Description: "拥有管理后台全部权限"},
	{Name: "运营负责人", Code: roleCodeOperationsLead, Description: "负责运营、团队、活动和日常配置管理"},
	{Name: "运营专员", Code: roleCodeOperationsSpecialist, Description: "负责日常运营执行，不含后台设置和高风险财务配置"},
	{Name: "产品负责人", Code: roleCodeProductLead, Description: "负责产品配置、资源、活动和游戏管理"},
	{Name: "产品专员", Code: roleCodeProductSpecialist, Description: "负责资源配置，并只读查看关联业务模块"},
	{Name: "财务负责人", Code: roleCodeFinanceLead, Description: "负责财务看板、充值对账和提现审核"},
	{Name: "财务专员", Code: roleCodeFinanceSpecialist, Description: "负责财务看板、充值对账和提现审核"},
}

var (
	workbenchOverview   = []string{"overview:view"}
	workbenchOperations = []string{
		"finance-order:coin-seller-recharge:view",
		"finance-order:coin-seller-recharge:create",
		"finance-order:coin-seller-recharge:verify",
		"finance-order:coin-seller-recharge:grant",
		"finance-order:usdt-address:update",
		"operations-withdrawal:view",
		"operations-withdrawal:audit",
	}
	workbenchFinance = []string{
		"finance:view",
		"payment-bill:view",
		"payment-bill:export",
		"finance-withdrawal:view",
		"finance-withdrawal:audit",
		"room-rps-order:view",
	}

	appUserRead = []string{
		"app-user:view", "app-user:export",
		"level-config:view", "pretty-id:view", "risk-config:view", "region-block:view",
	}
	appUserOperationsManage = []string{
		"app-user:update", "app-user:level", "app-user:status", "app-user:password",
		"level-config:update", "pretty-id:update", "pretty-id:grant", "risk-config:update", "region-block:update",
	}
	appUserProductManage = []string{
		"level-config:update", "pretty-id:update", "pretty-id:grant", "risk-config:update", "region-block:update",
	}

	teamRead = []string{
		"bd:view", "agency:view", "host:view",
		"host-agency-policy:view", "team-salary-policy:view", "host-salary-settlement:view",
		"coin-seller:view", "coin-seller-sub-application:view", "host-withdrawal:view", "point-withdrawal-config:view",
	}
	teamStructureManage = []string{
		"bd:create", "bd:update", "agency:create", "agency:status", "agency:delete",
	}
	teamLeadManage = []string{
		"host-agency-policy:create", "host-agency-policy:update", "host-agency-policy:delete", "host-agency-policy:publish",
		"team-salary-policy:create", "team-salary-policy:update", "team-salary-policy:delete",
		"host-salary-settlement:settle",
		"coin-seller:create", "coin-seller:update", "coin-seller:stock-credit", "coin-seller:exchange-rate",
		"coin-seller-sub-application:audit", "point-withdrawal-config:update",
	}

	roomRead = []string{
		"room:view", "room-pin:view", "room-config:view", "room-whitelist:view", "room-robot:view",
	}
	roomManage = []string{
		"room:update", "room:delete", "room-pin:create", "room-pin:cancel",
		"room-config:update", "room-whitelist:update", "room-robot:create", "room-robot:update",
	}

	appConfigRead = []string{
		"app-config:view", "app-version:view", "full-server-notice:view",
	}
	appConfigManage = []string{
		"app-config:update", "full-server-notice:send",
	}
	appVersionManage = []string{
		"app-version:create", "app-version:update", "app-version:delete",
	}

	resourceRead = []string{
		"resource:view", "resource-shop:view", "resource-group:view",
		"gift:view", "resource-grant:view", "emoji-pack:view",
	}
	resourceManage = []string{
		"resource:create", "resource:update", "resource:delete", "upload:create",
		"resource-shop:update", "resource-group:create", "resource-group:update", "resource-group:delete",
		"gift:create", "gift:update", "gift:status", "gift:delete",
		"resource-grant:create", "resource-grant:revoke", "emoji-pack:create",
	}

	operationsRead = []string{
		"gift-record:view", "coin-ledger:view", "coin-seller-ledger:view", "report:view",
	}
	operationsProductManage = []string{
		"gift-diamond:view", "gift-diamond:update",
	}
	operationsLeadManage = []string{
		"coin-adjustment:view", "coin-adjustment:create",
		"gift-diamond:view", "gift-diamond:update",
		"policy-template:view", "policy-template:create",
		"policy-instance:create", "policy-instance:update", "policy-instance:publish",
	}

	paymentRead = []string{
		"payment-bill:view", "payment-third-party:view", "payment-temporary-link:view", "payment-product:view",
	}
	paymentBillExport       = []string{"payment-bill:export"}
	paymentBillRefresh      = []string{"payment-bill:refresh"}
	paymentOperationsManage = []string{
		"payment-third-party:update-method", "payment-third-party:sync-methods",
		"payment-product:create", "payment-product:update", "payment-product:delete",
	}

	activityRead = []string{
		"activity-template:view", "activity-template:data",
		"daily-task:view", "first-recharge-reward:view", "cumulative-recharge-reward:view",
		"invite-activity-reward:view", "seven-day-checkin:view", "room-rocket:view", "room-turnover-reward:view",
		"wheel:view", "weekly-star:view", "agency-opening:view", "user-leaderboard:view", "red-packet:view",
		"cp-config:view", "cp-weekly-rank:view", "vip-config:view", "achievement:view", "lucky-gift:view",
	}
	activityManage = []string{
		"activity-template:create", "activity-template:update", "activity-template:publish", "activity-template:delete",
		"activity-template:export", "activity-template:retry",
		"daily-task:create", "daily-task:update", "daily-task:status",
		"first-recharge-reward:update", "cumulative-recharge-reward:update", "invite-activity-reward:update",
		"seven-day-checkin:update", "room-rocket:update", "room-turnover-reward:update", "room-turnover-reward:retry",
		"wheel:update", "weekly-star:create", "weekly-star:update", "weekly-star:settle",
		"agency-opening:create", "agency-opening:update", "red-packet:update",
		"cp-config:update", "cp-weekly-rank:update", "vip-config:update",
		"achievement:create", "achievement:update", "lucky-gift:update", "lucky-gift:experiment",
	}
	// 奖池人工增减属于资金高风险动作，只授予运营负责人；platform-admin 仍由全权限同步自动获得。
	luckyGiftPoolManage = []string{"lucky-gift:pool-credit", "lucky-gift:pool-debit"}

	gameRead = []string{
		"game-catalog:view", "self-game:view", "game-robot:view", "room-rps-config:view", "room-rps-order:view",
	}
	gameManage = []string{
		"game-catalog:platform", "game-catalog:create", "game-catalog:update", "game-catalog:status", "game-catalog:delete",
		"self-game:update",
		"game-robot:create", "game-robot:update", "game-robot:delete",
		"room-rps-config:update", "room-rps-order:update",
	}
	gameOperationsSpecialistManage = []string{
		"game-robot:create", "game-robot:update", "game-robot:delete", "room-rps-config:update",
	}

	geoRead   = []string{"country:view", "region:view"}
	geoManage = []string{"country:create", "country:update", "country:status", "region:create", "region:update", "region:status"}

	// 运营岗位只能查看和停用外管账号。创建、重置密码会签发或接管一组固定的
	// 高权限外管能力，必须收口到 platform-admin，避免运营角色委派自身并不具备的权限。
	externalAdminUserOperate = []string{
		"external-admin-user:view", "external-admin-user:status",
	}
)

// defaultRolePermissionCodes 只组合表格中明确勾选的模块。相同页面曾复用 game:* 或
// payment-third-party:update 的地方已经拆成页面级权限，避免为了一个按钮把相邻模块一起授权。
func defaultRolePermissionCodes(code string) []string {
	switch code {
	case roleCodeOperationsLead:
		return mergePermissionCodes(
			workbenchOverview, workbenchOperations,
			appUserRead, appUserOperationsManage,
			teamRead, teamStructureManage, teamLeadManage,
			roomRead, roomManage,
			[]string{"app-config:view"}, appConfigManage,
			resourceRead, resourceManage,
			operationsRead, operationsLeadManage, luckyGiftPoolManage,
			externalAdminUserOperate,
			paymentRead, paymentBillExport, paymentBillRefresh, paymentOperationsManage,
			activityRead, activityManage,
			gameRead, gameManage,
			geoRead, geoManage,
		)
	case roleCodeOperationsSpecialist:
		return mergePermissionCodes(
			workbenchOverview, workbenchOperations,
			appUserRead, appUserOperationsManage,
			teamRead, teamStructureManage,
			roomRead, roomManage,
			[]string{"app-config:view"}, appConfigManage,
			resourceRead, resourceManage,
			operationsRead,
			externalAdminUserOperate,
			paymentRead, paymentBillExport, paymentBillRefresh,
			activityRead,
			gameRead, gameOperationsSpecialistManage,
			geoRead,
		)
	case roleCodeProductLead:
		return mergePermissionCodes(
			workbenchOverview,
			appUserRead, appUserProductManage,
			teamRead,
			roomRead, roomManage,
			appConfigRead, appConfigManage, appVersionManage,
			resourceRead, resourceManage,
			operationsRead, operationsProductManage,
			paymentRead,
			activityRead, activityManage,
			gameRead, gameManage,
			geoRead,
		)
	case roleCodeProductSpecialist:
		return mergePermissionCodes(
			workbenchOverview,
			appUserRead,
			roomRead, []string{"room-robot:create", "room-robot:update"},
			appConfigRead,
			resourceRead, resourceManage,
			operationsRead,
			paymentRead,
			activityRead,
			gameRead,
			geoRead,
		)
	case roleCodeFinanceLead, roleCodeFinanceSpecialist:
		return mergePermissionCodes(workbenchOverview, workbenchFinance)
	default:
		return nil
	}
}

func mergePermissionCodes(groups ...[]string) []string {
	total := 0
	for _, group := range groups {
		total += len(group)
	}
	out := make([]string, 0, total)
	seen := make(map[string]struct{}, total)
	for _, group := range groups {
		for _, code := range group {
			if _, ok := seen[code]; ok {
				continue
			}
			seen[code] = struct{}{}
			out = append(out, code)
		}
	}
	return out
}
