/**
 * Check SharePoint Permissions
 * 
 * This script helps diagnose why SharePoint list creation is failing
 * 
 * Usage:
 *   node check-sharepoint-permissions.js
 */

require('dotenv').config({ path: './backend/.env' });
const { Companies } = require('./backend/models');
const { ensureFreshMsAccessToken } = require('./backend/utils/msTokenService');
const fetch = require('node-fetch');

async function checkPermissions() {
  try {
    console.log('🔍 Checking SharePoint Permissions...\n');
    
    // Get the company (assuming company ID 3 based on your logs)
    const companyId = process.argv[2] || 3;
    const company = await Companies.findByPk(companyId);
    
    if (!company) {
      console.error(`❌ Company ${companyId} not found`);
      process.exit(1);
    }
    
    console.log(`✅ Company found: ${company.name}`);
    console.log(`   MS Connected: ${company.msConnected}`);
    console.log(`   Site ID: ${company.msSharepointSiteId}\n`);
    
    // Get fresh access token
    const accessToken = await ensureFreshMsAccessToken(companyId);
    
    if (!accessToken) {
      console.error('❌ No access token available');
      process.exit(1);
    }
    
    console.log('✅ Access token obtained\n');
    
    // Check what permissions the token has
    console.log('📋 Checking token permissions...\n');
    
    // Try to get site info
    console.log('1️⃣ Testing: Get SharePoint site info');
    try {
      const siteResponse = await fetch('https://graph.microsoft.com/v1.0/sites/root', {
        headers: { Authorization: `Bearer ${accessToken}` }
      });
      
      if (siteResponse.ok) {
        const site = await siteResponse.json();
        console.log(`   ✅ Can read site: ${site.displayName}`);
        console.log(`   Site ID: ${site.id}\n`);
      } else {
        const error = await siteResponse.json();
        console.log(`   ❌ Cannot read site: ${error.error?.message || siteResponse.status}\n`);
      }
    } catch (e) {
      console.log(`   ❌ Error: ${e.message}\n`);
    }
    
    // Try to list existing lists
    console.log('2️⃣ Testing: List existing SharePoint lists');
    try {
      const listsResponse = await fetch(`https://graph.microsoft.com/v1.0/sites/${company.msSharepointSiteId}/lists`, {
        headers: { Authorization: `Bearer ${accessToken}` }
      });
      
      if (listsResponse.ok) {
        const lists = await listsResponse.json();
        console.log(`   ✅ Can read lists: Found ${lists.value.length} lists`);
        lists.value.forEach(list => {
          console.log(`      - ${list.displayName}`);
        });
        console.log('');
      } else {
        const error = await listsResponse.json();
        console.log(`   ❌ Cannot read lists: ${error.error?.message || listsResponse.status}\n`);
      }
    } catch (e) {
      console.log(`   ❌ Error: ${e.message}\n`);
    }
    
    // Try to create a test list
    console.log('3️⃣ Testing: Create a test SharePoint list');
    try {
      const createResponse = await fetch(`https://graph.microsoft.com/v1.0/sites/${company.msSharepointSiteId}/lists`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          displayName: 'NordSafe_Test_' + Date.now(),
          columns: [
            { name: 'Title', text: {} },
            { name: 'Description', text: { allowMultipleLines: true } }
          ],
          list: { template: 'genericList' }
        })
      });
      
      if (createResponse.ok) {
        const list = await createResponse.json();
        console.log(`   ✅ SUCCESS! Can create lists`);
        console.log(`   Created test list: ${list.displayName}`);
        console.log(`   List ID: ${list.id}\n`);
        
        // Clean up - delete the test list
        console.log('   🧹 Cleaning up test list...');
        await fetch(`https://graph.microsoft.com/v1.0/sites/${company.msSharepointSiteId}/lists/${list.id}`, {
          method: 'DELETE',
          headers: { Authorization: `Bearer ${accessToken}` }
        });
        console.log('   ✅ Test list deleted\n');
        
      } else {
        const error = await createResponse.json();
        console.log(`   ❌ CANNOT CREATE LISTS`);
        console.log(`   Status: ${createResponse.status}`);
        console.log(`   Error: ${error.error?.code}`);
        console.log(`   Message: ${error.error?.message}\n`);
        
        // Provide specific guidance based on error
        if (createResponse.status === 403) {
          console.log('📌 DIAGNOSIS: Permission Denied (403)\n');
          console.log('This means one of the following:');
          console.log('');
          console.log('1️⃣ The signed-in user needs SharePoint admin rights');
          console.log('   Solution: Make Ahmad.alhaffar@Nordsafe.onmicrosoft.com a SharePoint admin');
          console.log('   Go to: https://admin.microsoft.com → Users → Active users');
          console.log('   Select user → Roles → Assign "SharePoint Administrator" role\n');
          console.log('2️⃣ The app needs Application permissions (not just Delegated)');
          console.log('   Current: Using delegated permissions (acts as the user)');
          console.log('   Alternative: Use application permissions (acts as the app)\n');
          console.log('3️⃣ Admin consent not properly granted');
          console.log('   Go to Azure Portal → App registrations → Your app');
          console.log('   API permissions → Grant admin consent for Nordsafe\n');
        }
      }
    } catch (e) {
      console.log(`   ❌ Error: ${e.message}\n`);
    }
    
    console.log('═'.repeat(60));
    console.log('SUMMARY');
    console.log('═'.repeat(60));
    console.log('');
    console.log('If you see "❌ CANNOT CREATE LISTS" above, the issue is:');
    console.log('');
    console.log('👉 The signed-in user (Ahmad.alhaffar@Nordsafe.onmicrosoft.com)');
    console.log('   needs to be a SharePoint Administrator in your tenant.');
    console.log('');
    console.log('How to fix:');
    console.log('1. Go to https://admin.microsoft.com');
    console.log('2. Sign in as a Global Admin');
    console.log('3. Go to Users → Active users');
    console.log('4. Find Ahmad.alhaffar@Nordsafe.onmicrosoft.com');
    console.log('5. Click on the user → Manage roles');
    console.log('6. Select "SharePoint Administrator"');
    console.log('7. Save');
    console.log('8. Wait 5-10 minutes');
    console.log('9. Sign out and sign in again to your app');
    console.log('10. Try the auto-create button again');
    console.log('');
    
  } catch (error) {
    console.error('❌ Error:', error.message);
    console.error(error);
  } finally {
    process.exit(0);
  }
}

checkPermissions();
