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

/**
 * Canvas 模块 seed
 *
 * 职责：canvas page (admin 子节点) + canvas resource + 自家 SYSTEM_ADMIN 授权。
 * 前置：seedBootstrap 已建好 admin 与 SYSTEM_ADMIN。
 */
export async function seedCanvasModule(prisma: PrismaClient): Promise<void> {
  const role = await prisma.role.findUniqueOrThrow({
    where: { name: 'SYSTEM_ADMIN' },
  });
  const admin = await prisma.page.findUniqueOrThrow({
    where: { code: 'admin' },
  });

  const page = await upsertPage(prisma, {
    code: 'canvas',
    name: 'canvas',
    zhName: 'Canvas',
    enName: 'Canvas',
    sortOrder: 1010,
    parentId: admin.id,
  });
  console.log(`[canvas] Page: ${page.code} (id=${page.id})`);

  await bindResourceToPage(prisma, page.id, 'canvas', 'Canvas management');
  console.log(`[canvas] PageResource: canvas ↔ canvas`);

  const resourceIds = await getPageResourceIds(prisma, page.id);
  await grantRoleAccess(prisma, role.id, page.id, resourceIds);
  console.log(`[canvas] Grant: SYSTEM_ADMIN → canvas`);
}
