/**
 * Migrate Permissions
 *
 * Back-fills roleId on existing users that were created before the RBAC system
 * was introduced. For each user without a roleId:
 *   1. Finds the matching default role by the user's `role` string field
 *   2. Sets `roleId` to that role's _id
 *   3. Sets `status: 'active'` for users that don't have a status set
 *
 * Called from src/backend/src/index.ts on server startup, after seedRoles().
 */

import { getModels } from '../models';

// Mapping from User.role string to the default Role.name to link
const ROLE_NAME_MAP: Record<string, string> = {
  'super-admin': 'super-admin',
  'admin': 'admin',
  'manager': 'manager',
  'editor': 'editor',
  'viewer': 'viewer',
};

export async function migratePermissions(): Promise<void> {
  try {
    const { User, Role } = getModels();

    // Load all default roles once (name → _id)
    const roles = await Role.find({ name: { $in: Object.values(ROLE_NAME_MAP) } })
      .select('name _id')
      .lean();

    const roleMap = new Map<string, any>();
    for (const role of roles) {
      roleMap.set(role.name, role._id);
    }

    // Find all users that don't have a roleId set
    const users = await User.find({ roleId: { $exists: false } }).lean();

    if (users.length === 0) {
      console.log('[Migration] No users need roleId migration');
      return;
    }

    let migrated = 0;

    for (const user of users) {
      const targetRoleName = ROLE_NAME_MAP[user.role];
      if (!targetRoleName) {
        console.warn(`[Migration] Skipping user ${user.email || user._id}: unknown role "${user.role}"`);
        continue;
      }

      const roleId = roleMap.get(targetRoleName);
      if (!roleId) {
        console.warn(`[Migration] Skipping user ${user.email || user._id}: default role "${targetRoleName}" not found`);
        continue;
      }

      // Build update object — always set roleId; set status only if missing
      const update: Record<string, any> = { roleId };
      if (!user.status) {
        update.status = 'active';
      }

      await User.findByIdAndUpdate(user._id, update);
      migrated++;
    }

    console.log(`[Migration] Permissions: ${migrated} user(s) migrated (roleId set)`);
  } catch (error) {
    console.error('[Migration] Error migrating user permissions:', error);
    // Don't throw — migration failure shouldn't crash the server
  }
}