/**
 * Prisma Seed Entry Point
 * 
 * This file is the main entry for all database seeding.
 * Run: npm run db:seed
 * 
 * Individual seeds can also be run separately:
 *   - ts-node prisma/seeds/iam-seed.ts        # IAM (permissions, roles, workflow roles)
 *   - ts-node prisma/seeds/part-groups-seed.ts # Part groups with custom fields
 */

import { PrismaClient } from '@prisma/client';
import { seedIam } from './seeds/iam-seed';
import { seedPartGroups } from './seeds/part-groups-seed';
import { seedPositions } from './seeds/positions.seed';
import { seedDingtalkSync } from './seeds/dingtalk-sync.seed';
import { seedSyncBot } from './seeds/sync-bot.seed';
import { seedAiToolGrants } from './seeds/ai-tool-grants.seed';
import { seedPlatformMaster } from './seeds/platform-master-seed';
import { seedDefaultOrganization } from './seeds/default-organization.seed';

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Starting database seeding...\n');

  // 0. Seed default organization (幂等；裸 DB 必备，避免 OrganizationContext 拉空 → 全 API 400)
  console.log('🏢 Seeding default organization...');
  await seedDefaultOrganization(prisma);
  console.log('');

  // 1. Seed IAM data (permissions, roles, workflow roles)
  console.log('📋 Seeding IAM data...');
  await seedIam();
  console.log('');

  // 2. Seed Positions
  console.log('💼 Seeding Positions...');
  await seedPositions();
  console.log('');

  // 3. Seed Part Groups
  console.log('📦 Seeding Part Groups...');
  await seedPartGroups();
  console.log('');

  // 4. Seed DingTalk Sync
  console.log('🔄 Seeding DingTalk Sync...');
  await seedDingtalkSync();
  console.log('');

  // 5. Seed Sync Bot service account (v2.2 权限 MVP)
  console.log('🤖 Seeding Sync Bot service account...');
  await seedSyncBot();
  console.log('');

  // 6. Seed Robot Manager FieldDefs（32 unit + serviceType / locationType 系统字典）
  console.log('🤖 Seeding Robot Manager FieldDefs...');
  console.log('');

  // 7. Seed AI tool grants（除 SyncBot 外所有角色补齐 EMPLOYEE_BASELINE_TOOLS）
  console.log('🛠  Seeding AI tool grants...');
  await seedAiToolGrants(prisma);
  console.log('');

  // 8. Seed Platform Master 字典 / 参考数据（L1b）
  console.log('🌐 Seeding Platform Master dictionaries...');
  await seedPlatformMaster(prisma);
  console.log('');

  console.log('✅ All seeding completed successfully!');
}

main()
  .catch((e) => {
    console.error('❌ Seeding failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
