import { fileStorageService } from '../services/fileStorageService';
import { logger } from '../utils/logger';
import fs from 'fs';
import path from 'path';

async function testGCSIntegration() {
  logger.info('Starting GCS integration test...');

  try {
    // Test 1: Connection test
    logger.info('Test 1: Testing GCS connection...');
    const connectionTest = await fileStorageService.testConnection();
    if (!connectionTest) {
      logger.error('GCS connection test failed');
      return;
    }
    logger.info('✓ GCS connection test passed');

    // Test 2: Create a test file
    logger.info('Test 2: Creating test file...');
    const testContent = 'This is a test file for GCS integration testing.';
    const testFilePath = path.join(__dirname, 'test-file.txt');
    fs.writeFileSync(testFilePath, testContent);

    const mockFile = {
      originalname: 'test-file.txt',
      filename: 'test-file.txt',
      path: testFilePath,
      size: testContent.length,
      mimetype: 'text/plain',
    };

    // Test 3: Upload file to GCS
    logger.info('Test 3: Uploading file to GCS...');
    const uploadResult = await fileStorageService.storeFile(mockFile, 'test-user-123');
    if (!uploadResult.success || !uploadResult.fileInfo) {
      logger.error('File upload failed:', uploadResult.error);
      return;
    }
    logger.info('✓ File uploaded successfully:', uploadResult.fileInfo);

    const gcsPath = uploadResult.fileInfo.gcsPath!;

    // Test 4: Check if file exists
    logger.info('Test 4: Checking if file exists...');
    const exists = await fileStorageService.fileExists(gcsPath);
    if (!exists) {
      logger.error('File existence check failed');
      return;
    }
    logger.info('✓ File exists check passed');

    // Test 5: Get file info
    logger.info('Test 5: Getting file info...');
    const fileInfo = await fileStorageService.getFileInfo(gcsPath);
    if (!fileInfo) {
      logger.error('Get file info failed');
      return;
    }
    logger.info('✓ File info retrieved:', fileInfo);

    // Test 6: Get file size
    logger.info('Test 6: Getting file size...');
    const fileSize = await fileStorageService.getFileSize(gcsPath);
    if (fileSize === null) {
      logger.error('Get file size failed');
      return;
    }
    logger.info(`✓ File size: ${fileSize} bytes`);

    // Test 7: Download file
    logger.info('Test 7: Downloading file...');
    const downloadedContent = await fileStorageService.getFile(gcsPath);
    if (!downloadedContent) {
      logger.error('File download failed');
      return;
    }
    const downloadedText = downloadedContent.toString();
    if (downloadedText !== testContent) {
      logger.error('Downloaded content does not match original');
      return;
    }
    logger.info('✓ File download and content verification passed');

    // Test 8: Generate signed URL
    logger.info('Test 8: Generating signed URL...');
    const signedUrl = await fileStorageService.generateSignedUrl(gcsPath, 60);
    if (!signedUrl) {
      logger.error('Signed URL generation failed');
      return;
    }
    logger.info('✓ Signed URL generated:', signedUrl);

    // Test 9: Copy file
    logger.info('Test 9: Copying file...');
    const copyPath = `${gcsPath}-copy`;
    const copySuccess = await fileStorageService.copyFile(gcsPath, copyPath);
    if (!copySuccess) {
      logger.error('File copy failed');
      return;
    }
    logger.info('✓ File copied successfully');

    // Test 10: List files
    logger.info('Test 10: Listing files...');
    const files = await fileStorageService.listFiles('uploads/test-user-123/', 10);
    logger.info(`✓ Found ${files.length} files in user directory`);

    // Test 11: Get storage stats
    logger.info('Test 11: Getting storage stats...');
    const stats = await fileStorageService.getStorageStats('uploads/test-user-123/');
    logger.info('✓ Storage stats:', stats);

    // Test 12: Move file
    logger.info('Test 12: Moving file...');
    const movePath = `${gcsPath}-moved`;
    const moveSuccess = await fileStorageService.moveFile(copyPath, movePath);
    if (!moveSuccess) {
      logger.error('File move failed');
      return;
    }
    logger.info('✓ File moved successfully');

    // Test 13: Clean up test files
    logger.info('Test 13: Cleaning up test files...');
    const deleteOriginal = await fileStorageService.deleteFile(gcsPath);
    const deleteMoved = await fileStorageService.deleteFile(movePath);
    
    if (!deleteOriginal || !deleteMoved) {
      logger.error('File cleanup failed');
      return;
    }
    logger.info('✓ Test files cleaned up successfully');

    // Clean up local test file
    if (fs.existsSync(testFilePath)) {
      fs.unlinkSync(testFilePath);
    }

    logger.info('🎉 All GCS integration tests passed successfully!');

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

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

export { testGCSIntegration }; 