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 via SQL...\n');
  
  try {
    // Try to create tables using the SQL editor approach
    console.log('🔄 Attempting to create tables...');
    
    // Create users table
    console.log('Creating users table...');
    const { error: usersError } = await serviceClient
      .from('users')
      .select('*')
      .limit(0); // This will fail if table doesn't exist, but we can catch the error
    
    if (usersError && usersError.message.includes('does not exist')) {
      console.log('❌ Users table does not exist - need to create via SQL editor');
    } else {
      console.log('✅ Users table exists');
    }
    
    // Create documents table
    console.log('Creating documents table...');
    const { error: docsError } = await serviceClient
      .from('documents')
      .select('*')
      .limit(0);
    
    if (docsError && docsError.message.includes('does not exist')) {
      console.log('❌ Documents table does not exist - need to create via SQL editor');
    } else {
      console.log('✅ Documents table exists');
    }
    
    console.log('\n📋 Tables need to be created via Supabase SQL Editor');
    console.log('Please run the following SQL in your Supabase dashboard:');
    console.log('\n--- SQL TO RUN IN SUPABASE DASHBOARD ---');
    console.log(`
-- Create users table
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
);

-- Create documents table
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
);

-- Create document_versions table
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
);

-- Create document_feedback table
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
);

-- Create processing_jobs table
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
);

-- Create 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);
    `);
    console.log('--- END SQL ---\n');
    
    console.log('📝 Instructions:');
    console.log('1. Go to your Supabase dashboard');
    console.log('2. Navigate to SQL Editor');
    console.log('3. Paste the SQL above and run it');
    console.log('4. Come back and test the application');
    
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

createTables(); 