/**
 * Sync Bot Service Account Seed
 *
 * 权限 MVP v2.2：为 OpenClaw 同步脚本创建专用服务账号 `sync-bot`。
 *
 * 该账号只用于：OpenClaw 侧的 cron 同步脚本以 loopback 方式调用 Workspace API
 * （`GET /users?externalId=<AAD GUID>` 和 `GET /ai-tools/user-effective/:userId`），
 * 拉 AI 工具授权做 per-user 合并后写回 OpenClaw config。
 *
 * ⚠️ 密码处理：seed 创建用户时 `passwordHash=null`，这样账号存在但无法登录。
 * 每套环境部署后，运维需要在各服务器上手动设置密码：
 *
 *   ```bash
 *   # 1. 生成 bcrypt 哈希
 *   node -e "require('bcrypt').hash('<strong-random-password>', 10).then(console.log)"
 *
 *   # 2. 直接 UPDATE 数据库
 *   psql -c "UPDATE platform_iam.users SET password_hash='<hash>' WHERE username='sync-bot'"
 *
 *   # 3. 将密码写入同步脚本的 cron env 文件
 *   echo 'WORKSPACE_SYNC_BOT_PASSWORD=<strong-random-password>' >> /srv/apps/<env>/.env.sync
 *   ```
 *
 * 详见 openclaw 仓 `docs/enterprise-plan/solution/governance/permissions-mvp-plan.md`
 * 「实施顺序第 4 步 OpenClaw 同步脚本」章节。
 */

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const SYNC_BOT_USERNAME = 'sync-bot';
const SYNC_BOT_EMAIL = 'sync-bot@ffai.internal';
const SYNC_BOT_DISPLAY_NAME = 'OpenClaw Sync Bot';
const SYNC_BOT_ROLE_CODE = 'SyncBot';

export async function seedSyncBot() {
  console.log('🤖 Seeding sync-bot service account...');

  // 1. Find the SyncBot role (created by seedIam via roles.seed.ts)
  const syncBotRole = await prisma.role.findUnique({
    where: { code: SYNC_BOT_ROLE_CODE },
  });
  if (!syncBotRole) {
    throw new Error(
      `SyncBot role not found. Run seedIam() first to create it from roles.seed.ts`,
    );
  }

  // 2. Upsert sync-bot user (passwordHash stays null — ops must set it manually per env)
  const user = await prisma.user.upsert({
    where: { username: SYNC_BOT_USERNAME },
    update: {
      // Keep existing passwordHash on update (don't clobber ops-set password)
      email: SYNC_BOT_EMAIL,
      displayName: SYNC_BOT_DISPLAY_NAME,
      status: 'ACTIVE',
      source: 'LOCAL',
    },
    create: {
      username: SYNC_BOT_USERNAME,
      email: SYNC_BOT_EMAIL,
      displayName: SYNC_BOT_DISPLAY_NAME,
      status: 'ACTIVE',
      source: 'LOCAL',
      passwordHash: null, // ops must set manually per environment
    },
  });
  console.log(`  ✅ sync-bot user ready (id=${user.id})`);

  // 3. Assign SyncBot role globally (organizationId = null → 跨所有组织可读)
  //
  // 不用 upsert：Prisma 的 `userId_roleId_organizationId` 复合 unique 在 organizationId 为 null 时
  // 无法精确匹配（SQL NULL 语义），所以用 findFirst + create 避免类型 cast
  const existing = await prisma.userRole.findFirst({
    where: {
      userId: user.id,
      roleId: syncBotRole.id,
      organizationId: null,
    },
  });
  if (!existing) {
    await prisma.userRole.create({
      data: {
        userId: user.id,
        roleId: syncBotRole.id,
        organizationId: null,
      },
    });
  }
  console.log(`  ✅ sync-bot assigned SyncBot role (global scope)`);

  console.log('✅ Sync bot seeding completed!');
}

// If running directly
if (require.main === module) {
  seedSyncBot()
    .then(() => {
      console.log('✅ Sync bot seed completed successfully');
      process.exit(0);
    })
    .catch((e) => {
      console.error('❌ Error seeding sync-bot:', e);
      process.exit(1);
    })
    .finally(async () => {
      void prisma.$disconnect();
    });
}
