/**
 * Test CV upload matching the exact API implementation
 * Simulates what happens at line 132 of /app/api/apply-job/route.ts
 */

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

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

// Constant from lib/supabase.ts line 128
const JOB_CV_BUCKET = 'job-cvs';

async function testAPIUpload() {
  console.log('🧪 Testing API CV Upload (matching line 132 implementation)...\n');

  const supabaseAdmin = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);

  // Simulate API request data
  const now = new Date();
  const jobSlug = 'senior-developer';
  const applicantName = 'test-applicant';
  const baseFilename = 'cv';
  const filePath = `${jobSlug}/${now.getTime()}-${applicantName}-${baseFilename}.pdf`;

  // Simulate CV file content
  const resumeBuffer = Buffer.from(`
    TEST CV DOCUMENT
    ================
    Name: Test Applicant
    Position: Senior Developer

    This is a test CV upload matching the exact API implementation
    at line 132 of /app/api/apply-job/route.ts
  `);

  console.log(`📤 Upload Configuration:`);
  console.log(`   Bucket: ${JOB_CV_BUCKET}`);
  console.log(`   Path: ${filePath}`);
  console.log(`   Size: ${resumeBuffer.length} bytes`);
  console.log(`   Content-Type: application/pdf`);

  try {
    // Exact code from line 132-138
    const { error: uploadError } = await supabaseAdmin.storage
      .from(JOB_CV_BUCKET)
      .upload(filePath, resumeBuffer, {
        contentType: 'application/pdf',
        cacheControl: '3600',
        upsert: false,
      });

    if (uploadError) {
      console.error('\n❌ Failed to upload CV to Supabase Storage', uploadError);
      console.error('\n⚠️  API would return: { error: "Failed to upload CV, please try again later" }, status: 500');
      process.exit(1);
    }

    console.log('\n✅ Upload successful! (matching line 132-138)');
    console.log('   File uploaded to:', filePath);
    console.log('   Storage path:', `${JOB_CV_BUCKET}/${filePath}`);

    // Test cleanup (matching line 175)
    console.log('\n🧹 Testing cleanup (line 175)...');
    await supabaseAdmin.storage.from(JOB_CV_BUCKET).remove([filePath]);
    console.log('✅ Cleanup successful!');

    console.log('\n' + '='.repeat(60));
    console.log('✅ API CV UPLOAD TEST PASSED');
    console.log('='.repeat(60));
    console.log('The /app/api/apply-job/route.ts endpoint will work correctly!');
    console.log('Line 132 upload operation: ✅ FUNCTIONAL');
    console.log('Line 175 cleanup operation: ✅ FUNCTIONAL');
    console.log('='.repeat(60));

  } catch (error) {
    console.error('\n❌ Test failed:', error.message);
    console.error('\nFull error:', error);
    console.error('\n⚠️  The API endpoint at line 132 would fail with this error.');
    process.exit(1);
  }
}

testAPIUpload();
