import { PrismaClient } from '@prisma/client';
import {
  bindResourceToPage,
  getPageResourceIds,
  grantRoleAccess,
  upsertPage,
} from '../scripts/lib/page-helpers';
import { seedWorkflowEventTrigger } from './workflow-event-trigger';
import { seedNodeTypes } from './workflow-node-types';

/**
 * Workflow 模块 seed
 *
 * 一站式负责 workflow 模块所有 seed：
 *   1. 菜单结构：workflow 父分组 + 2 个 leaf (workflow_list / workflow_node_instance)
 *   2. resource: workflow / workflowNodeInstance
 *   3. PageResource 绑定与 SYSTEM_ADMIN 授权
 *   4. 业务数据：node-types / workflows / event-trigger function & index
 *
 * 业务数据 seed 函数仍来自 ./workflow-{node-types,workflows,event-trigger}.ts
 * （文件较大，保持独立但只被本入口 import，不再由 seed/index.ts 直接调用）。
 *
 * 前置：seedBootstrap 已建好 admin 与 SYSTEM_ADMIN。
 */
export async function seedWorkflowModule(prisma: PrismaClient): Promise<void> {
  const role = await prisma.role.findUniqueOrThrow({
    where: { name: 'SYSTEM_ADMIN' },
  });
  const admin = await prisma.page.findUniqueOrThrow({
    where: { code: 'admin' },
  });

  // ── 父分组 page ────────────────────────────────────────────────────────────
  const workflowPage = await upsertPage(prisma, {
    code: 'workflow',
    name: 'workflow',
    zhName: 'Workflow',
    enName: 'Workflow',
    sortOrder: 1030,
    parentId: admin.id,
  });
  console.log(`[workflow] Page: ${workflowPage.code} (id=${workflowPage.id})`);

  // ── leaf pages + resource 绑定 ─────────────────────────────────────────────
  const leafDefs: {
    code: string;
    zhName: string;
    enName: string;
    sortOrder: number;
    resourceCode: string;
    resourceDescription: string;
  }[] = [
    {
      code: 'workflow_list',
      zhName: '工作流列表',
      enName: 'List',
      sortOrder: 1,
      resourceCode: 'workflow',
      resourceDescription: 'Workflow management',
    },
    {
      code: 'workflow_node_instance',
      zhName: 'Node模版',
      enName: 'Node Instance',
      sortOrder: 2,
      resourceCode: 'workflowNodeInstance',
      resourceDescription: 'Workflow node instance management',
    },
  ];

  const allPages = [{ id: workflowPage.id, code: workflowPage.code }];

  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: workflowPage.id,
    });
    allPages.push({ id: p.id, code: p.code });
    console.log(`[workflow] Page: ${p.code} (id=${p.id})`);

    await bindResourceToPage(
      prisma,
      p.id,
      def.resourceCode,
      def.resourceDescription,
    );
    console.log(`[workflow] PageResource: ${def.code} ↔ ${def.resourceCode}`);
  }

  // ── SYSTEM_ADMIN 授权 ──────────────────────────────────────────────────────
  for (const p of allPages) {
    const resourceIds = await getPageResourceIds(prisma, p.id);
    await grantRoleAccess(prisma, role.id, p.id, resourceIds);
    console.log(
      `[workflow] Grant: SYSTEM_ADMIN → ${p.code} (+${resourceIds.length} resource)`,
    );
  }

  // ── 业务数据 ───────────────────────────────────────────────────────────────
  await seedNodeTypes(prisma);
  await seedWorkflowEventTrigger(prisma);
}
