import { db } from './db';
import { sql } from 'drizzle-orm';

export async function createMtnMobileSyncProgressTable(): Promise<void> {
  try {
    console.log('Creating MTN Mobile Sync Progress table...');
    
    // Create the table
    await db.execute(sql`
      CREATE TABLE IF NOT EXISTS mtn_mobile_sync_progress (
        id SERIAL PRIMARY KEY,
        session_id VARCHAR(100) NOT NULL,
        username VARCHAR(255) NOT NULL,
        total_accounts INTEGER NOT NULL,
        processed_accounts INTEGER NOT NULL DEFAULT 0,
        current_account VARCHAR(255),
        current_status VARCHAR(255),
        total_days INTEGER NOT NULL DEFAULT 0,
        processed_days INTEGER NOT NULL DEFAULT 0,
        errors TEXT[] DEFAULT '{}',
        is_completed BOOLEAN NOT NULL DEFAULT false,
        is_cancelled BOOLEAN NOT NULL DEFAULT false,
        started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        completed_at TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
      )
    `);

    // Add the is_cancelled column if it doesn't exist (for existing deployments)
    await db.execute(sql`
      ALTER TABLE mtn_mobile_sync_progress 
      ADD COLUMN IF NOT EXISTS is_cancelled BOOLEAN NOT NULL DEFAULT false
    `);

    console.log('MTN Mobile Sync Progress table created successfully');
  } catch (error) {
    console.error('Error creating MTN Mobile Sync Progress table:', error);
    throw error;
  }
}