/**
 * Script to initialize all permissions in the backend API
 * Usage: npx tsx scripts/init-permissions.ts
 * Or: node scripts/init-permissions.js (after compiling)
 */

import { PERMISSIONS_MOCK } from '../src/app/core/mocks/role.mocks';

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

// Clean up permissions: remove duplicates by name and fix IDs
const uniquePermissions = Array.from(
  new Map(
    PERMISSIONS_MOCK.map((p) => [p.name, p])
  ).values()
).map((p, index) => ({
  name: p.name,
  description: p.description || '',
}));

interface PermissionPayload {
  name: string;
  description: string;
}

async function createPermission(payload: PermissionPayload): Promise<{ success: boolean; data?: any; error?: string }> {
  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: any) {
    return {
      success: false,
      error: error.message || 'Unknown error',
    };
  }
}

async function getAllExistingPermissions(): Promise<Set<string>> {
  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: any) => 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);
});

