const { createClient } = require('@supabase/supabase-js');

// Supabase configuration from environment
const SUPABASE_URL = 'https://gzoclmbqmgmpuhufbnhy.supabase.co';
const SUPABASE_SERVICE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imd6b2NsbWJxbWdtcHVodWZibmh5Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc1MzgxNjY3OCwiZXhwIjoyMDY5MzkyNjc4fQ.f9PUzL1F8JqIkqD_DwrGBIyHPcehMo-97jXD8hee5ss';

const serviceClient = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);

async function createTables() {
  console.log('Creating Supabase database tables...\n');
  
  try {
    // Create users table
    console.log('🔄 Creating users table...');
    const { error: usersError } = await serviceClient.rpc('exec_sql', {
      sql: `
        CREATE TABLE IF NOT EXISTS users (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          firebase_uid VARCHAR(255) UNIQUE NOT NULL,
          name VARCHAR(255),
          email VARCHAR(255) UNIQUE NOT NULL,
          created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
        );
      `
    });
    
    if (usersError) {
      console.log(`❌ Users table error: ${usersError.message}`);
    } else {
      console.log('✅ Users table created successfully');
    }
    
    // Create documents table
    console.log('\n🔄 Creating documents table...');
    const { error: docsError } = await serviceClient.rpc('exec_sql', {
      sql: `
        CREATE TABLE IF NOT EXISTS documents (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          user_id VARCHAR(255) NOT NULL,
          original_file_name VARCHAR(255) NOT NULL,
          file_path TEXT NOT NULL,
          file_size BIGINT NOT NULL,
          status VARCHAR(50) DEFAULT 'uploaded',
          extracted_text TEXT,
          generated_summary TEXT,
          error_message TEXT,
          analysis_data JSONB,
          processing_completed_at TIMESTAMP WITH TIME ZONE,
          created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
        );
      `
    });
    
    if (docsError) {
      console.log(`❌ Documents table error: ${docsError.message}`);
    } else {
      console.log('✅ Documents table created successfully');
    }
    
    // Create document_versions table
    console.log('\n🔄 Creating document_versions table...');
    const { error: versionsError } = await serviceClient.rpc('exec_sql', {
      sql: `
        CREATE TABLE IF NOT EXISTS document_versions (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
          version_number INTEGER NOT NULL,
          file_path TEXT NOT NULL,
          processing_strategy VARCHAR(50),
          created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
        );
      `
    });
    
    if (versionsError) {
      console.log(`❌ Document versions table error: ${versionsError.message}`);
    } else {
      console.log('✅ Document versions table created successfully');
    }
    
    // Create document_feedback table
    console.log('\n🔄 Creating document_feedback table...');
    const { error: feedbackError } = await serviceClient.rpc('exec_sql', {
      sql: `
        CREATE TABLE IF NOT EXISTS document_feedback (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
          user_id VARCHAR(255) NOT NULL,
          feedback_type VARCHAR(50) NOT NULL,
          feedback_text TEXT,
          rating INTEGER CHECK (rating >= 1 AND rating <= 5),
          created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
        );
      `
    });
    
    if (feedbackError) {
      console.log(`❌ Document feedback table error: ${feedbackError.message}`);
    } else {
      console.log('✅ Document feedback table created successfully');
    }
    
    // Create processing_jobs table
    console.log('\n🔄 Creating processing_jobs table...');
    const { error: jobsError } = await serviceClient.rpc('exec_sql', {
      sql: `
        CREATE TABLE IF NOT EXISTS processing_jobs (
          id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
          job_type VARCHAR(50) NOT NULL,
          status VARCHAR(50) DEFAULT 'pending',
          data JSONB NOT NULL,
          priority INTEGER DEFAULT 0,
          started_at TIMESTAMP WITH TIME ZONE,
          completed_at TIMESTAMP WITH TIME ZONE,
          error_message TEXT,
          created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
        );
      `
    });
    
    if (jobsError) {
      console.log(`❌ Processing jobs table error: ${jobsError.message}`);
    } else {
      console.log('✅ Processing jobs table created successfully');
    }
    
    // Create indexes
    console.log('\n🔄 Creating indexes...');
    const indexes = [
      'CREATE INDEX IF NOT EXISTS idx_documents_user_id ON documents(user_id);',
      'CREATE INDEX IF NOT EXISTS idx_documents_status ON documents(status);',
      'CREATE INDEX IF NOT EXISTS idx_processing_jobs_status ON processing_jobs(status);',
      'CREATE INDEX IF NOT EXISTS idx_processing_jobs_priority ON processing_jobs(priority);'
    ];
    
    for (const indexSql of indexes) {
      const { error: indexError } = await serviceClient.rpc('exec_sql', { sql: indexSql });
      if (indexError) {
        console.log(`❌ Index creation error: ${indexError.message}`);
      }
    }
    
    console.log('✅ Indexes created successfully');
    
    console.log('\n🎉 All tables created successfully!');
    
    // Verify tables exist
    console.log('\n🔍 Verifying tables...');
    const tables = ['users', 'documents', 'document_versions', 'document_feedback', 'processing_jobs'];
    
    for (const table of tables) {
      const { data, error } = await serviceClient
        .from(table)
        .select('*')
        .limit(1);
      
      if (error) {
        console.log(`❌ Table ${table} verification failed: ${error.message}`);
      } else {
        console.log(`✅ Table ${table} verified successfully`);
      }
    }
    
  } catch (error) {
    console.error('❌ Table creation failed:', error.message);
    console.error('Error details:', error);
  }
}

createTables(); 