/**
 * AI 工具授权种子 - 给所有非 SyncBot 角色补齐 EMPLOYEE_BASELINE_TOOLS。
 * 幂等：(roleId, toolName) 已存在则跳过。
 *
 * 单一来源：复用 backend/src/modules/organization/ai-tools/available-tools.config.ts
 * 该文件无外部依赖（纯常量），可被 ts-node 直接加载，不会触发 NestJS 依赖链。
 */
import { PrismaClient } from '@prisma/client';
import { EMPLOYEE_BASELINE_TOOLS } from '../../src/modules/organization/ai-tools/available-tools.config';

const SYNCBOT_CODE = 'SyncBot';

export async function seedAiToolGrants(prisma?: PrismaClient) {
  const client = prisma ?? new PrismaClient();
  const ownsClient = !prisma;

  try {
    const roles = await client.role.findMany({
      where: { code: { not: SYNCBOT_CODE } },
      select: { id: true, name: true, code: true },
    });

    let totalCreated = 0;
    let totalSkipped = 0;

    for (const role of roles) {
      let created = 0;
      let skipped = 0;

      for (const toolName of EMPLOYEE_BASELINE_TOOLS) {
        const existing = await client.aIToolGrant.findUnique({
          where: { roleId_toolName: { roleId: role.id, toolName } },
        });
        if (existing) {
          skipped++;
          continue;
        }
        await client.aIToolGrant.create({
          data: { roleId: role.id, toolName },
        });
        created++;
      }

      console.log(
        `  ${role.name} (${role.code}): +${created} created, ${skipped} skipped`,
      );
      totalCreated += created;
      totalSkipped += skipped;
    }

    console.log(
      `  ✓ ${roles.length} roles processed: +${totalCreated} created, ${totalSkipped} skipped.`,
    );
  } finally {
    if (ownsClient) {
      await client.$disconnect();
    }
  }
}

if (require.main === module) {
  seedAiToolGrants()
    .catch((e) => {
      console.error('❌ Seed failed:', e);
      process.exit(1);
    });
}
