/**
 * Script to initialize all permissions in the backend API
 * Usage: node scripts/init-permissions.js
 * Or: npm run init-permissions
 */

const PERMISSIONS_DATA = [
  // Users
  { name: 'USERS_READ', description: 'Voir utilisateurs' },
  { name: 'USERS_CREATE', description: 'Créer utilisateurs' },
  { name: 'USERS_UPDATE', description: 'Modifier utilisateurs' },
  { name: 'USERS_DELETE', description: 'Supprimer utilisateurs' },
  { name: 'USERS_RESET_PASSWORD', description: 'Réinitialiser mot de passe' },
  { name: 'USERS_LOCK', description: 'Verrouiller utilisateurs' },
  { name: 'USERS_UNLOCK', description: 'Déverrouiller utilisateurs' },
  { name: 'USERS_RESET_2FA', description: 'Réinitialiser 2FA' },
  { name: 'USERS_CHANGE_ROLE', description: 'Changer de rôle' },
  { name: 'USERS_CHANGE_STATUS', description: 'Changer de statut' },

  // Hippodromes
  { name: 'HIPPODROMES_READ', description: 'Voir hippodromes' },
  { name: 'HIPPODROMES_CREATE', description: 'Créer hippodromes' },
  { name: 'HIPPODROMES_UPDATE', description: 'Modifier hippodromes' },
  { name: 'HIPPODROMES_DELETE', description: 'Supprimer hippodromes' },

  // Reunions
  { name: 'REUNIONS_READ', description: 'Voir reunions' },
  { name: 'REUNIONS_CREATE', description: 'Créer reunions' },
  { name: 'REUNIONS_UPDATE', description: 'Modifier reunions' },
  { name: 'REUNIONS_DELETE', description: 'Supprimer reunions' },
  { name: 'REUNIONS_PLANIFIEE', description: 'Planifier reunions' },
  { name: 'REUNIONS_TERMINEE', description: 'Terminer les reunions' },
  { name: 'REUNIONS_CANCEL', description: 'Annuler les reunions' },

  // Courses
  { name: 'COURSES_READ', description: 'Voir courses' },
  { name: 'COURSES_CREATE', description: 'Créer courses' },
  { name: 'COURSES_UPDATE', description: 'Modifier courses' },
  { name: 'COURSES_DELETE', description: 'Supprimer courses' },
  { name: 'COURSES_VALIDATE', description: 'Valider courses' },
  { name: 'COURSES_CONFIRM', description: 'Confirmer courses' },
  { name: 'COURSES_CLOSE', description: 'Clôturer courses' },
  { name: 'COURSES_CANCEL', description: 'Annuler courses' },

  // TPE
  { name: 'TPE_READ', description: 'Voir TPE' },
  { name: 'TPE_CREATE', description: 'Créer TPE' },
  { name: 'TPE_UPDATE', description: 'Modifier TPE' },
  { name: 'TPE_DELETE', description: 'Supprimer TPE' },
  { name: 'TPE_ASSIGN', description: 'Assigner TPE' },
  { name: 'TPE_UNASSIGN', description: 'Déassigner TPE' },

  // Agents
  { name: 'AGENTS_READ', description: 'Voir agents' },
  { name: 'AGENTS_CREATE', description: 'Créer agents' },
  { name: 'AGENTS_UPDATE', description: 'Modifier agents' },
  { name: 'AGENTS_DELETE', description: 'Supprimer agents' },
  { name: 'AGENTS_ASSIGN', description: 'Assigner agents' },
  { name: 'AGENTS_UNASSIGN', description: 'Déassigner agents' },
  { name: 'AGENTS_ASSIGN_TPE', description: 'Assigner TPE à agents' },
  { name: 'AGENTS_UNASSIGN_TPE', description: 'Déassigner TPE à agents' },

  // Familles Agents
  { name: 'AGENT_FAMILIES_READ', description: 'Voir familles agents' },
  { name: 'AGENT_FAMILIES_CREATE', description: 'Créer familles agents' },
  { name: 'AGENT_FAMILIES_UPDATE', description: 'Modifier familles agents' },
  { name: 'AGENT_FAMILIES_DELETE', description: 'Supprimer familles agents' },

  // Limites Agents
  { name: 'AGENT_LIMITS_READ', description: 'Voir limites agents' },
  { name: 'AGENT_LIMITS_CREATE', description: 'Créer limites agents' },
  { name: 'AGENT_LIMITS_UPDATE', description: 'Modifier limites agents' },
  { name: 'AGENT_LIMITS_DELETE', description: 'Supprimer limites agents' },
  { name: 'AGENT_LIMITS_DEFAULTED', description: 'Définir limites agents par défaut' },

  // Permissions
  { name: 'PERMISSIONS_READ', description: 'Voir permissions' },
  { name: 'PERMISSIONS_CREATE', description: 'Créer permissions' },
  { name: 'PERMISSIONS_UPDATE', description: 'Modifier permissions' },
  { name: 'PERMISSIONS_DELETE', description: 'Supprimer permissions' },
  { name: 'PERMISSIONS_ASSIGN', description: 'Assigner permissions' },
  { name: 'PERMISSIONS_UNASSIGN', description: 'Déassigner permissions' },

  // Roles
  { name: 'ROLES_READ', description: 'Voir rôles' },
  { name: 'ROLES_CREATE', description: 'Créer rôles' },
  { name: 'ROLES_UPDATE', description: 'Modifier rôles' },
  { name: 'ROLES_DELETE', description: 'Supprimer rôles' },
  { name: 'ROLES_ASSIGN', description: 'Assigner rôles' },
  { name: 'ROLES_UNASSIGN', description: 'Déassigner rôles' },
  { name: 'ROLES_ASSIGN_PERMISSIONS', description: 'Assigner permissions à rôles' },
  { name: 'ROLES_UNASSIGN_PERMISSIONS', description: 'Déassigner permissions à rôles' },
];

// Remove duplicates by name
const uniquePermissions = Array.from(new Map(PERMISSIONS_DATA.map((p) => [p.name, p])).values());

const API_BASE_URL = process.env.API_BASE_URL || 'https://b440a25a7658.ngrok-free.app';
const PERMISSIONS_ENDPOINT = `${API_BASE_URL}/api/v1/permissions`;

async function createPermission(payload) {
  try {
    const response = await fetch(PERMISSIONS_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'ngrok-skip-browser-warning': 'true',
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const errorText = await response.text();
      return {
        success: false,
        error: `HTTP ${response.status}: ${errorText}`,
      };
    }

    const data = await response.json();
    return { success: true, data };
  } catch (error) {
    return {
      success: false,
      error: error.message || 'Unknown error',
    };
  }
}

async function getAllExistingPermissions() {
  try {
    const response = await fetch(PERMISSIONS_ENDPOINT, {
      headers: {
        'ngrok-skip-browser-warning': 'true',
      },
    });
    if (response.ok) {
      const data = await response.json();
      const permissions = Array.isArray(data) ? data : [];
      return new Set(permissions.map((p) => p.name).filter(Boolean));
    }
    return new Set();
  } catch (error) {
    console.warn('Warning: Could not fetch existing permissions, will try to create all:', error);
    return new Set();
  }
}

async function initAllPermissions() {
  console.log(`🚀 Initializing ${uniquePermissions.length} permissions...\n`);
  console.log(`API Base URL: ${API_BASE_URL}\n`);

  // Fetch all existing permissions once at the start
  console.log('📋 Fetching existing permissions...');
  const existingPermissions = await getAllExistingPermissions();
  console.log(`   Found ${existingPermissions.size} existing permission(s)\n`);

  const results = {
    created: 0,
    skipped: 0,
    errors: 0,
  };

  for (const perm of uniquePermissions) {
    // Check if permission already exists in the set we fetched
    if (existingPermissions.has(perm.name)) {
      console.log(`⏭️  Skipped: ${perm.name} (already exists)`);
      results.skipped++;
      continue;
    }

    const result = await createPermission({
      name: perm.name,
      description: perm.description || '',
    });

    if (result.success) {
      console.log(`✅ Created: ${perm.name}`);
      results.created++;
    } else {
      console.error(`❌ Failed: ${perm.name} - ${result.error}`);
      results.errors++;
    }

    // Small delay to avoid overwhelming the server
    await new Promise((resolve) => setTimeout(resolve, 100));
  }

  console.log(`\n📊 Summary:`);
  console.log(`   Created: ${results.created}`);
  console.log(`   Skipped: ${results.skipped}`);
  console.log(`   Errors: ${results.errors}`);
  console.log(`   Total: ${uniquePermissions.length}`);
}

// Run the script
initAllPermissions().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});
