#!/usr/bin/env node

/**
 * Test CV Download Functionality
 * Tests the staff CV download endpoint
 */

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

config({ path: '.env.local' });

const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL;
const SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!SUPABASE_URL || !SERVICE_ROLE_KEY) {
  console.error('❌ Missing Supabase configuration');
  process.exit(1);
}

const supabaseAdmin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
  auth: {
    autoRefreshToken: false,
    persistSession: false,
  },
});

async function testCVDownload() {
  console.log('🔍 Testing CV Download Functionality\n');

  // Get a test application
  const { data: application, error: appError } = await supabaseAdmin
    .from('job_applications')
    .select('id, applicant_name, cv_bucket, cv_path, cv_filename')
    .limit(1)
    .single();

  if (appError || !application) {
    console.error('❌ No applications found:', appError);
    process.exit(1);
  }

  console.log('✅ Found application:');
  console.log(`   ID: ${application.id}`);
  console.log(`   Applicant: ${application.applicant_name}`);
  console.log(`   CV Bucket: ${application.cv_bucket}`);
  console.log(`   CV Path: ${application.cv_path}`);
  console.log(`   CV Filename: ${application.cv_filename}\n`);

  // Try to download the CV
  console.log('📥 Attempting to download CV from Supabase Storage...');

  const { data: cvData, error: storageError } = await supabaseAdmin.storage
    .from(application.cv_bucket)
    .download(application.cv_path);

  if (storageError) {
    console.error('❌ Storage download error:', storageError);
    console.error('   Message:', storageError.message);
    console.error('   Status:', storageError.statusCode);

    // Check if file exists
    console.log('\n🔍 Checking if file exists in storage...');
    const { data: fileList, error: listError } = await supabaseAdmin.storage
      .from(application.cv_bucket)
      .list(application.cv_path.split('/')[0], { limit: 100 });

    if (listError) {
      console.error('❌ Cannot list files:', listError);
    } else {
      console.log(`✅ Found ${fileList?.length || 0} files in folder`);
      fileList?.forEach(file => {
        console.log(`   - ${file.name} (${file.metadata?.size || 0} bytes)`);
      });
    }

    process.exit(1);
  }

  console.log('✅ CV downloaded successfully!');
  console.log(`   Size: ${cvData.size} bytes`);
  console.log(`   Type: ${cvData.type}\n`);

  // Save to temp file for verification
  const buffer = Buffer.from(await cvData.arrayBuffer());
  const tempFile = `/tmp/test-download-${Date.now()}.pdf`;
  fs.writeFileSync(tempFile, buffer);

  console.log(`✅ CV saved to: ${tempFile}`);
  console.log(`   File size: ${buffer.length} bytes`);
  console.log(`   First bytes: ${buffer.subarray(0, 8).toString('utf-8')}`);

  // Verify it's a valid PDF
  if (buffer.subarray(0, 4).toString() === '%PDF') {
    console.log('✅ Valid PDF file!');
  } else {
    console.log('⚠️  File may not be a valid PDF');
  }

  console.log('\n✅ CV download test PASSED!');
}

testCVDownload().catch(error => {
  console.error('❌ Test failed:', error);
  process.exit(1);
});
