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

/**
 * Agenda 模块 seed
 *
 * 职责：agenda page (admin 子节点) + agenda resource + 自家 SYSTEM_ADMIN 授权。
 * 前置：seedBootstrap 已建好 admin 与 SYSTEM_ADMIN。
 */
export async function seedAgendaModule(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: 'agenda',
    name: 'agenda',
    zhName: 'Cron Jobs',
    enName: 'Cron Jobs',
    sortOrder: 1020,
    parentId: admin.id,
  });
  console.log(`[agenda] Page: ${page.code} (id=${page.id})`);

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

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