/**
 * Direct test of CV upload to job-cvs bucket
 */

import { createClient } from '@supabase/supabase-js';

const SUPABASE_URL = 'http://localhost:54321';
const SUPABASE_SERVICE_ROLE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';

async function testUpload() {
  console.log('🧪 Testing CV Upload to job-cvs bucket...\n');

  const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);

  try {
    // Create test content
    const testContent = Buffer.from('This is a test CV file for verification');
    const testPath = `applications/test-${Date.now()}.pdf`;

    console.log(`📤 Uploading test file: ${testPath}`);

    // Attempt upload
    const { data, error } = await supabase.storage
      .from('job-cvs')
      .upload(testPath, testContent, {
        contentType: 'application/pdf',
        upsert: false
      });

    if (error) {
      console.error('❌ Upload failed:', error);
      throw error;
    }

    console.log('✅ Upload successful!');
    console.log('   Path:', data.path);
    console.log('   Full path:', data.fullPath);

    // Get public URL (even though bucket is private, we can get the path)
    const { data: urlData } = supabase.storage
      .from('job-cvs')
      .getPublicUrl(testPath);

    console.log('   Storage URL:', urlData.publicUrl);

    // Try to download
    console.log('\n📥 Downloading file...');
    const { data: downloadData, error: downloadError } = await supabase.storage
      .from('job-cvs')
      .download(testPath);

    if (downloadError) {
      console.error('❌ Download failed:', downloadError);
    } else {
      console.log(`✅ Download successful (${downloadData.size} bytes)`);
    }

    // Clean up
    console.log('\n🧹 Cleaning up...');
    const { error: deleteError } = await supabase.storage
      .from('job-cvs')
      .remove([testPath]);

    if (deleteError) {
      console.error('⚠️  Delete failed:', deleteError);
    } else {
      console.log('✅ Test file deleted');
    }

    console.log('\n' + '='.repeat(60));
    console.log('✅ CV UPLOAD TEST PASSED');
    console.log('='.repeat(60));
    console.log('The job-cvs bucket is ready for production use!');
    console.log('Applications can now upload CV files successfully.');
    console.log('='.repeat(60));

  } catch (error) {
    console.error('\n❌ Test failed:', error.message);
    console.error('Full error:', error);
    process.exit(1);
  }
}

testUpload();
