import { Router } from 'express'

import {
  listAdminRolesWithPermissions,
  updateAdminRolePermissions,
} from '../../services/admin/admin-rbac-service.js'
import { createJsonHandler, requireAdminRoles } from './session.js'

const router = Router()

router.use('/rbac', requireAdminRoles(['admin']))

router.get(
  '/rbac',
  createJsonHandler(() => listAdminRolesWithPermissions(), {
    successMessage: 'ok',
    errorMessage: '读取角色权限失败',
    scope: '[admin/rbac]',
  }),
)

router.put(
  '/rbac/roles/:roleKey/permissions',
  createJsonHandler(
    (req) => updateAdminRolePermissions(req.params.roleKey, req.body?.permissions),
    {
      successMessage: '角色权限已更新',
      errorMessage: '更新角色权限失败',
      scope: '[admin/rbac/roles/:roleKey/permissions]',
      audit: (req, data) => ({
        action: 'admin_role_permissions_updated',
        targetType: 'admin_role',
        targetId: String(req.params.roleKey || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

export default router
