import { Storage } from '@google-cloud/storage';
import { config } from '../config/env';
import { logger } from '../utils/logger';

async function setupGCSPermissions() {
  logger.info('Setting up GCS permissions and bucket configuration...');

  try {
    // Initialize Google Cloud Storage
    const storage = new Storage({
      keyFilename: config.googleCloud.applicationCredentials,
      projectId: config.googleCloud.projectId,
    });

    const bucketName = config.googleCloud.gcsBucketName;
    const bucket = storage.bucket(bucketName);

    logger.info(`Checking bucket: ${bucketName}`);

    // Check if bucket exists
    const [exists] = await bucket.exists();
    if (!exists) {
      logger.error(`Bucket ${bucketName} does not exist!`);
      logger.info('Please create the bucket first using one of these methods:');
      logger.info('');
      logger.info('Method 1: Using gcloud CLI');
      logger.info(`gcloud storage buckets create gs://${bucketName} --project=${config.googleCloud.projectId} --location=us-central1 --uniform-bucket-level-access`);
      logger.info('');
      logger.info('Method 2: Using Google Cloud Console');
      logger.info('1. Go to https://console.cloud.google.com/storage/browser');
      logger.info(`2. Click "Create Bucket"`);
      logger.info(`3. Enter bucket name: ${bucketName}`);
      logger.info('4. Choose location: us-central1 (or your preferred region)');
      logger.info('5. Choose storage class: Standard');
      logger.info('6. Choose access control: Uniform bucket-level access');
      logger.info('7. Click "Create"');
      logger.info('');
      return;
    }

    logger.info(`✓ Bucket ${bucketName} exists`);

    // Check bucket permissions
    try {
      const [metadata] = await bucket.getMetadata();
      logger.info('✓ Bucket metadata retrieved successfully');
      logger.info(`Bucket location: ${metadata.location}`);
      logger.info(`Bucket storage class: ${metadata.storageClass}`);
      logger.info(`Uniform bucket-level access: ${metadata.iamConfiguration?.uniformBucketLevelAccess?.enabled ? 'Enabled' : 'Disabled'}`);
    } catch (error) {
      logger.error('Failed to get bucket metadata:', error);
      logger.info('This indicates a permissions issue.');
    }

    // Test basic operations
    logger.info('Testing basic bucket operations...');

    try {
      // Test listing files (requires storage.objects.list permission)
      await bucket.getFiles({ maxResults: 1 });
      logger.info('✓ Can list files in bucket');
    } catch (error) {
      logger.error('Cannot list files in bucket:', error);
    }

    try {
      // Test creating a test file (requires storage.objects.create permission)
      const testFile = bucket.file('test-permissions.txt');
      await testFile.save('test content', {
        metadata: {
          contentType: 'text/plain',
        },
      });
      logger.info('✓ Can create files in bucket');

      // Clean up test file
      await testFile.delete();
      logger.info('✓ Can delete files in bucket');
    } catch (error) {
      logger.error('Cannot create/delete files in bucket:', error);
    }

    // Provide setup instructions
    logger.info('');
    logger.info('=== GCS Setup Instructions ===');
    logger.info('');
    logger.info('If you encountered permission errors, follow these steps:');
    logger.info('');
    logger.info('1. Go to Google Cloud Console IAM:');
    logger.info('   https://console.cloud.google.com/iam-admin/iam');
    logger.info('');
    logger.info('2. Find your service account:');
    logger.info(`   ${config.googleCloud.applicationCredentials}`);
    logger.info('');
    logger.info('3. Add the following roles:');
    logger.info('   - Storage Object Admin (for full access)');
    logger.info('   - Storage Object Viewer (for read-only access)');
    logger.info('   - Storage Admin (for bucket management)');
    logger.info('');
    logger.info('4. Or use gcloud CLI:');
    logger.info(`gcloud projects add-iam-policy-binding ${config.googleCloud.projectId} \\`);
    logger.info(`    --member="serviceAccount:cim-document-processor@${config.googleCloud.projectId}.iam.gserviceaccount.com" \\`);
    logger.info('    --role="roles/storage.objectAdmin"');
    logger.info('');
    logger.info('5. For bucket-level permissions:');
    logger.info(`gcloud storage buckets add-iam-policy-binding gs://${bucketName} \\`);
    logger.info(`    --member="serviceAccount:cim-document-processor@${config.googleCloud.projectId}.iam.gserviceaccount.com" \\`);
    logger.info('    --role="roles/storage.objectAdmin"');
    logger.info('');
    logger.info('6. Test the setup:');
    logger.info('   npm run test:gcs');
    logger.info('');

  } catch (error) {
    logger.error('GCS setup failed:', error);
  }
}

// Run the setup if this script is executed directly
if (require.main === module) {
  setupGCSPermissions()
    .then(() => {
      logger.info('GCS setup completed');
      process.exit(0);
    })
    .catch((error) => {
      logger.error('GCS setup failed:', error);
      process.exit(1);
    });
}

export { setupGCSPermissions }; 