/**
 * Verify job-cvs bucket creation and test upload
 */

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

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

async function verifyBucket() {
  console.log('🚀 Verifying CV Bucket Setup...\n');

  const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, {
    auth: {
      autoRefreshToken: false,
      persistSession: false
    }
  });

  try {
    // Step 1: List all buckets
    console.log('📦 Step 1: Listing all buckets...');
    const { data: buckets, error: listError } = await supabase.storage.listBuckets();

    if (listError) {
      console.error('❌ Error listing buckets:', listError);
      throw listError;
    }

    console.log(`✅ Found ${buckets.length} bucket(s)`);
    buckets.forEach(b => {
      console.log(`   - ${b.id} (created: ${b.created_at})`);
    });

    // Step 2: Check if job-cvs exists
    console.log('\n🔍 Step 2: Checking for job-cvs bucket...');
    const cvBucket = buckets.find(b => b.id === 'job-cvs');

    if (!cvBucket) {
      console.error('❌ job-cvs bucket not found!');
      process.exit(1);
    }

    console.log('✅ job-cvs bucket exists');
    console.log('   Bucket details:', JSON.stringify(cvBucket, null, 2));

    // Step 3: Test upload
    console.log('\n🧪 Step 3: Testing file upload...');
    const testContent = Buffer.from('Test CV content for verification');
    const testPath = `test-uploads/verify-${Date.now()}.pdf`;

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

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

    console.log('✅ Upload successful:', uploadData.path);

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

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

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

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

    // Summary
    console.log('\n' + '='.repeat(60));
    console.log('📊 VERIFICATION SUMMARY');
    console.log('='.repeat(60));
    console.log('Bucket ID:     job-cvs');
    console.log('Status:        ✅ EXISTS AND FUNCTIONAL');
    console.log('Upload Test:   ✅ PASSED');
    console.log('Download Test: ✅ PASSED');
    console.log('Delete Test:   ✅ PASSED');
    console.log('='.repeat(60));
    console.log('\n✅ All tests passed! Bucket is ready for CV uploads.');

  } catch (error) {
    console.error('\n❌ Fatal Error:', error);
    process.exit(1);
  }
}

verifyBucket();
