#!/usr/bin/env node

/**
 * Pre-Deployment Storage Bucket Validation Script
 *
 * Purpose: Ensure all required Supabase storage buckets exist and are properly configured
 * Usage: npm run validate:storage-buckets
 *
 * This prevents the Nov 18, 2025 job application failure issue from happening again.
 *
 * Exit Codes:
 * 0 = All validations passed
 * 1 = Validation failures detected (DO NOT DEPLOY)
 */

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

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

const REQUIRED_BUCKETS = [
  {
    id: 'job-cvs',
    name: 'job-cvs',
    description: 'Job application CV uploads',
    critical: true, // If missing, job applications will fail
    requiredPolicies: ['INSERT', 'SELECT', 'DELETE'],
  },
];

// Colors for terminal output
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  cyan: '\x1b[36m',
};

function log(message, color = colors.reset) {
  console.log(`${color}${message}${colors.reset}`);
}

function logSuccess(message) {
  log(`✅ ${message}`, colors.green);
}

function logError(message) {
  log(`❌ ${message}`, colors.red);
}

function logWarning(message) {
  log(`⚠️  ${message}`, colors.yellow);
}

function logInfo(message) {
  log(`ℹ️  ${message}`, colors.cyan);
}

async function validateStorageBuckets() {
  log('\n' + '='.repeat(80), colors.bright);
  log('STORAGE BUCKET VALIDATION - Pre-Deployment Check', colors.bright);
  log('='.repeat(80) + '\n', colors.bright);

  // Check environment variables
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

  if (!supabaseUrl || !supabaseKey) {
    logError('Missing Supabase configuration!');
    logInfo('Required: NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY');
    logInfo('Check your .env.local file');
    process.exit(1);
  }

  // Create Supabase admin client
  const supabase = createClient(supabaseUrl, supabaseKey, {
    auth: {
      autoRefreshToken: false,
      persistSession: false,
    },
  });

  logInfo(`Checking Supabase instance: ${supabaseUrl}`);
  console.log('');

  let hasErrors = false;
  let hasCriticalErrors = false;

  // Check each bucket individually by attempting to upload a test file
  // Note: listBuckets() SDK method doesn't work with current Supabase version
  let existingBuckets = [];

  logInfo('Checking required buckets...');
  for (const bucket of REQUIRED_BUCKETS) {
    // Try a test upload to see if bucket is accessible
    const testFile = `validation-check-${Date.now()}.txt`;
    const testContent = Buffer.from('validation-test');

    const { error: uploadError } = await supabase.storage
      .from(bucket.id)
      .upload(testFile, testContent);

    if (!uploadError) {
      existingBuckets.push({ id: bucket.id, name: bucket.id });

      // Clean up test file
      await supabase.storage.from(bucket.id).remove([testFile]);
    } else if (uploadError.message?.includes('Duplicate')) {
      // Bucket exists but file already there (shouldn't happen with timestamp)
      existingBuckets.push({ id: bucket.id, name: bucket.id });
    }
    // If error is "Bucket not found", bucket doesn't exist
  }

  logInfo(`Found ${existingBuckets?.length || 0} existing storage buckets`);
  console.log('');

  // Validate each required bucket
  for (const requiredBucket of REQUIRED_BUCKETS) {
    log(`Checking bucket: ${requiredBucket.id}`, colors.bright);
    logInfo(`Description: ${requiredBucket.description}`);

    const bucket = existingBuckets?.find(b => b.id === requiredBucket.id);

    if (!bucket) {
      if (requiredBucket.critical) {
        logError(`CRITICAL: Bucket '${requiredBucket.id}' does not exist!`);
        logError(`Impact: ${requiredBucket.description} will fail in production`);
        logInfo(`Fix: Run migration 20251118_create_job_cvs_bucket.sql`);
        hasCriticalErrors = true;
      } else {
        logWarning(`Bucket '${requiredBucket.id}' does not exist`);
      }
      hasErrors = true;
      console.log('');
      continue;
    }

    logSuccess(`Bucket '${requiredBucket.id}' exists`);

    // Test bucket permissions
    const testFileName = `validation-test-${Date.now()}.txt`;
    const testContent = Buffer.from('validation test');

    // Test INSERT permission
    const { error: uploadError } = await supabase.storage
      .from(requiredBucket.id)
      .upload(testFileName, testContent);

    if (uploadError) {
      logError(`Cannot upload to bucket '${requiredBucket.id}': ${uploadError.message}`);
      logInfo('Check: RLS policies on storage.objects table');
      hasErrors = true;
    } else {
      logSuccess('INSERT permission: OK');

      // Test SELECT permission
      const { error: downloadError } = await supabase.storage
        .from(requiredBucket.id)
        .download(testFileName);

      if (downloadError) {
        logError(`Cannot download from bucket '${requiredBucket.id}': ${downloadError.message}`);
        hasErrors = true;
      } else {
        logSuccess('SELECT permission: OK');
      }

      // Test DELETE permission
      const { error: deleteError } = await supabase.storage
        .from(requiredBucket.id)
        .remove([testFileName]);

      if (deleteError) {
        logError(`Cannot delete from bucket '${requiredBucket.id}': ${deleteError.message}`);
        hasErrors = true;
      } else {
        logSuccess('DELETE permission: OK');
      }
    }

    console.log('');
  }

  // Final summary
  log('='.repeat(80), colors.bright);
  if (hasCriticalErrors) {
    logError('CRITICAL ERRORS DETECTED - DO NOT DEPLOY!');
    log('='.repeat(80), colors.bright);
    logError('Fix all critical issues before deploying to production');
    process.exit(1);
  } else if (hasErrors) {
    logWarning('WARNINGS DETECTED - Review before deploying');
    log('='.repeat(80), colors.bright);
    process.exit(1);
  } else {
    logSuccess('ALL STORAGE BUCKET VALIDATIONS PASSED');
    log('='.repeat(80), colors.bright);
    logSuccess('Safe to deploy!');
    process.exit(0);
  }
}

// Run validation
validateStorageBuckets().catch(error => {
  logError(`Unexpected error: ${error.message}`);
  console.error(error);
  process.exit(1);
});
