import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import pkg from 'pg';
const { Pool } = pkg;
import { sql } from 'drizzle-orm';

/**
 * Data-only migration script to move existing user emails to email_accounts
 * Assumes tables already exist from Drizzle migrations
 */

const pool = new Pool({
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '5432'),
  user: process.env.DB_USER || 'admin',
  password: process.env.DB_PASSWORD || 'heslo123',
  database: process.env.DB_NAME || 'crm',
});

const db = drizzle(pool);

async function migrateData() {
  console.log('🚀 Starting data migration to email accounts...\n');

  try {
    // Step 1: Check if email_accounts table exists
    console.log('Step 1: Checking email_accounts table...');
    const tableExists = await db.execute(sql`
      SELECT EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_schema = 'public'
        AND table_name = 'email_accounts'
      )
    `);

    if (!tableExists.rows[0].exists) {
      throw new Error('email_accounts table does not exist. Run Drizzle migrations first.');
    }
    console.log('✅ email_accounts table exists\n');

    // Step 2: Migrate existing user emails to email_accounts
    console.log('Step 2: Migrating existing user emails to email_accounts...');
    const usersWithEmail = await db.execute(sql`
      SELECT id, email, email_password, jmap_account_id
      FROM users
      WHERE email IS NOT NULL
        AND email_password IS NOT NULL
        AND jmap_account_id IS NOT NULL
    `);

    console.log(`Found ${usersWithEmail.rows.length} users with email accounts`);

    for (const user of usersWithEmail.rows) {
      // Check if already migrated
      const existing = await db.execute(sql`
        SELECT id FROM email_accounts
        WHERE user_id = ${user.id} AND email = ${user.email}
      `);

      if (existing.rows.length > 0) {
        console.log(`  ⏩ Skipping user ${user.id}: ${user.email} (already migrated)`);
        continue;
      }

      await db.execute(sql`
        INSERT INTO email_accounts (user_id, email, email_password, jmap_account_id, is_primary, is_active)
        VALUES (${user.id}, ${user.email}, ${user.email_password}, ${user.jmap_account_id}, true, true)
      `);
      console.log(`  ✓ Migrated email account for user ${user.id}: ${user.email}`);
    }
    console.log('✅ User emails migrated\n');

    // Step 3: Update existing contacts with email_account_id
    console.log('Step 3: Updating existing contacts with email_account_id...');
    const contactsNeedUpdate = await db.execute(sql`
      SELECT COUNT(*) as count FROM contacts WHERE email_account_id IS NULL
    `);

    if (parseInt(contactsNeedUpdate.rows[0].count) > 0) {
      await db.execute(sql`
        UPDATE contacts
        SET email_account_id = (
          SELECT ea.id
          FROM email_accounts ea
          WHERE ea.user_id = contacts.user_id
            AND ea.is_primary = true
          LIMIT 1
        )
        WHERE email_account_id IS NULL
      `);
      console.log(`✅ Updated ${contactsNeedUpdate.rows[0].count} contacts\n`);
    } else {
      console.log('✅ No contacts to update\n');
    }

    // Step 4: Update existing emails with email_account_id
    console.log('Step 4: Updating existing emails with email_account_id...');
    const emailsNeedUpdate = await db.execute(sql`
      SELECT COUNT(*) as count FROM emails WHERE email_account_id IS NULL
    `);

    if (parseInt(emailsNeedUpdate.rows[0].count) > 0) {
      await db.execute(sql`
        UPDATE emails
        SET email_account_id = (
          SELECT ea.id
          FROM email_accounts ea
          WHERE ea.user_id = emails.user_id
            AND ea.is_primary = true
          LIMIT 1
        )
        WHERE email_account_id IS NULL
      `);
      console.log(`✅ Updated ${emailsNeedUpdate.rows[0].count} emails\n`);
    } else {
      console.log('✅ No emails to update\n');
    }

    // Summary
    console.log('🎉 Data migration completed successfully!\n');
    console.log('Summary:');
    console.log(`  - Email accounts migrated: ${usersWithEmail.rows.length}`);
    console.log(`  - Contacts updated: ${contactsNeedUpdate.rows[0].count}`);
    console.log(`  - Emails updated: ${emailsNeedUpdate.rows[0].count}`);

  } catch (error) {
    console.error('❌ Migration failed:', error);
    throw error;
  } finally {
    await pool.end();
  }
}

// Run migration
migrateData().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});
