import { PrismaClient } from '@prisma/client';
import {
  bindResourceToPage,
  getPageResourceIds,
  grantRoleAccess,
  upsertPage,
} from '../scripts/lib/page-helpers';

/**
 * Permission 模块 seed
 *
 * 职责（仅本模块自家）：
 *   1. permission 父分组 page (admin → permission)
 *   2. 5 个 leaf page: permission_readme / user / role / page / resource
 *   3. 7 个 resource: user / role / rolePages / roleResource / page / pageResource / resource
 *   4. PageResource 绑定（page ↔ resource，多对多）
 *   5. SYSTEM_ADMIN 对上述全部 page + resource 的全量授权
 *
 * 前置：seedBootstrap 已建好 admin 顶级 page 和 SYSTEM_ADMIN role。
 *
 * 多 resource 共享同一 page 的情况（如 role page UI 同时调 role + rolePages + roleResource API）
 * 通过 resourceDefs[].pageCode 表达。
 */
export async function seedPermissionModule(
  prisma: PrismaClient,
): Promise<void> {
  // ── 前置查找 ───────────────────────────────────────────────────────────────
  const systemAdminRole = await prisma.role.findUniqueOrThrow({
    where: { name: 'SYSTEM_ADMIN' },
  });
  const adminPage = await prisma.page.findUniqueOrThrow({
    where: { code: 'admin' },
  });

  // ── permission 父分组 ──────────────────────────────────────────────────────
  const permissionPage = await upsertPage(prisma, {
    code: 'permission',
    name: 'permission',
    zhName: '权限管理',
    enName: 'Permission Mgnt',
    sortOrder: 1040,
    parentId: adminPage.id,
  });
  console.log(
    `[permission] Page: ${permissionPage.code} (id=${permissionPage.id})`,
  );

  // ── leaf pages ─────────────────────────────────────────────────────────────
  const leafDefs = [
    {
      code: 'permission_readme',
      zhName: '菜单指引',
      enName: 'Menu Guide',
      sortOrder: 1005,
    },
    { code: 'user', zhName: '用户管理', enName: 'User Mgnt', sortOrder: 1010 },
    { code: 'role', zhName: '角色管理', enName: 'Role Mgnt', sortOrder: 1020 },
    { code: 'page', zhName: '页面管理', enName: 'Page Mgnt', sortOrder: 1030 },
    {
      code: 'resource',
      zhName: '资源管理',
      enName: 'Resource Management',
      sortOrder: 1040,
    },
  ];

  const pagesByCode = new Map<string, number>();
  pagesByCode.set(permissionPage.code, permissionPage.id);

  for (const def of leafDefs) {
    const p = await upsertPage(prisma, {
      code: def.code,
      name: def.code,
      zhName: def.zhName,
      enName: def.enName,
      sortOrder: def.sortOrder,
      parentId: permissionPage.id,
    });
    pagesByCode.set(p.code, p.id);
    console.log(`[permission] Page: ${p.code} (id=${p.id})`);
  }

  // ── resource ↔ page 绑定 ───────────────────────────────────────────────────
  const resourceDefs: {
    code: string;
    description: string;
    pageCode: string;
  }[] = [
    { code: 'user', description: 'User management', pageCode: 'user' },
    { code: 'role', description: 'Role management', pageCode: 'role' },
    {
      code: 'rolePages',
      description: 'Role-page assignments',
      pageCode: 'role',
    },
    {
      code: 'roleResource',
      description: 'Role-resource grants',
      pageCode: 'role',
    },
    { code: 'page', description: 'Page / menu management', pageCode: 'page' },
    {
      code: 'pageResource',
      description: 'Page-resource configuration',
      pageCode: 'page',
    },
    {
      code: 'resource',
      description: 'Resource management',
      pageCode: 'resource',
    },
  ];

  for (const def of resourceDefs) {
    const pageId = pagesByCode.get(def.pageCode);
    if (!pageId)
      throw new Error(`[permission] Page not found: ${def.pageCode}`);
    await bindResourceToPage(prisma, pageId, def.code, def.description);
    console.log(`[permission] PageResource: ${def.pageCode} ↔ ${def.code}`);
  }

  // ── SYSTEM_ADMIN 授权（page + resource） ────────────────────────────────────
  for (const [code, pageId] of pagesByCode) {
    const resourceIds = await getPageResourceIds(prisma, pageId);
    await grantRoleAccess(prisma, systemAdminRole.id, pageId, resourceIds);
    console.log(
      `[permission] Grant: SYSTEM_ADMIN → ${code} (+${resourceIds.length} resource)`,
    );
  }
}
