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

/**
 * Audit 模块 seed
 *
 * 职责：audits page (admin 子节点) + audit resource + 自家 SYSTEM_ADMIN 授权。
 * 注意：page.code 是 'audits'，但 resource.code 是 'audit'（与 backend module 一致）。
 * 前置：seedBootstrap 已建好 admin 与 SYSTEM_ADMIN。
 */
export async function seedAuditModule(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: 'audits',
    name: 'audits',
    zhName: '审计日志',
    enName: 'Audit Log',
    sortOrder: 1060,
    parentId: admin.id,
  });
  console.log(`[audit] Page: ${page.code} (id=${page.id})`);

  await bindResourceToPage(prisma, page.id, 'audit', 'Audit logs');
  console.log(`[audit] PageResource: audits ↔ audit`);

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