import { db } from '../config/database.js';
import { sql } from 'drizzle-orm';
import { logger } from '../utils/logger.js';

/**
 * Fresh database - vymaže všetky tabuľky a vytvorí ich znova
 *
 * ⚠️  POZOR: Tento script vymaže všetky dáta!
 * Použite len na development alebo pri začiatku s novými dátami.
 */
async function freshDatabase() {
  try {
    logger.warn('\n⚠️  POZOR: Tento script vymaže všetky dáta!');
    logger.warn('   Čaká sa 5 sekúnd... Stlač Ctrl+C na zrušenie.\n');

    // Wait 5 seconds
    await new Promise(resolve => setTimeout(resolve, 5000));

    logger.info('🔄 Dropping all tables...');

    // Drop all tables in correct order (reverse of dependencies)
    await db.execute(sql`DROP TABLE IF EXISTS emails CASCADE`);
    logger.success('  ✅ Dropped table: emails');

    await db.execute(sql`DROP TABLE IF EXISTS contacts CASCADE`);
    logger.success('  ✅ Dropped table: contacts');

    await db.execute(sql`DROP TABLE IF EXISTS user_email_accounts CASCADE`);
    logger.success('  ✅ Dropped table: user_email_accounts');

    await db.execute(sql`DROP TABLE IF EXISTS email_accounts CASCADE`);
    logger.success('  ✅ Dropped table: email_accounts');

    await db.execute(sql`DROP TABLE IF EXISTS audit_logs CASCADE`);
    logger.success('  ✅ Dropped table: audit_logs');

    await db.execute(sql`DROP TABLE IF EXISTS users CASCADE`);
    logger.success('  ✅ Dropped table: users');

    await db.execute(sql`DROP TYPE IF EXISTS role CASCADE`);
    logger.success('  ✅ Dropped type: role');

    logger.info('\n🔨 Creating all tables...');

    // Create role enum
    await db.execute(sql`CREATE TYPE role AS ENUM ('admin', 'member')`);
    logger.success('  ✅ Created type: role');

    // Create users table
    await db.execute(sql`
      CREATE TABLE users (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        username TEXT NOT NULL UNIQUE,
        first_name TEXT,
        last_name TEXT,
        password TEXT,
        temp_password TEXT,
        changed_password BOOLEAN NOT NULL DEFAULT false,
        role role NOT NULL DEFAULT 'member',
        last_login TIMESTAMP,
        created_at TIMESTAMP NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMP NOT NULL DEFAULT NOW()
      )
    `);
    logger.success('  ✅ Created table: users');

    // Create email_accounts table
    await db.execute(sql`
      CREATE TABLE email_accounts (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        email TEXT NOT NULL UNIQUE,
        email_password TEXT NOT NULL,
        jmap_account_id TEXT NOT NULL,
        is_active BOOLEAN NOT NULL DEFAULT true,
        created_at TIMESTAMP NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMP NOT NULL DEFAULT NOW()
      )
    `);
    logger.success('  ✅ Created table: email_accounts');

    // Create user_email_accounts junction table
    await db.execute(sql`
      CREATE TABLE user_email_accounts (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        email_account_id UUID NOT NULL REFERENCES email_accounts(id) ON DELETE CASCADE,
        is_primary BOOLEAN NOT NULL DEFAULT false,
        added_at TIMESTAMP NOT NULL DEFAULT NOW(),
        UNIQUE(user_id, email_account_id)
      )
    `);
    logger.success('  ✅ Created table: user_email_accounts');

    // Create contacts table
    await db.execute(sql`
      CREATE TABLE contacts (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        email_account_id UUID NOT NULL REFERENCES email_accounts(id) ON DELETE CASCADE,
        email TEXT NOT NULL,
        name TEXT,
        notes TEXT,
        added_by UUID REFERENCES users(id) ON DELETE SET NULL,
        added_at TIMESTAMP NOT NULL DEFAULT NOW(),
        created_at TIMESTAMP NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
        UNIQUE(email_account_id, email)
      )
    `);
    logger.success('  ✅ Created table: contacts');

    // Create emails table
    await db.execute(sql`
      CREATE TABLE emails (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        email_account_id UUID NOT NULL REFERENCES email_accounts(id) ON DELETE CASCADE,
        contact_id UUID REFERENCES contacts(id) ON DELETE CASCADE,
        jmap_id TEXT UNIQUE,
        message_id TEXT UNIQUE,
        thread_id TEXT,
        in_reply_to TEXT,
        "from" TEXT,
        "to" TEXT,
        subject TEXT,
        body TEXT,
        is_read BOOLEAN NOT NULL DEFAULT false,
        sent_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
        date TIMESTAMP,
        created_at TIMESTAMP NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMP NOT NULL DEFAULT NOW()
      )
    `);
    logger.success('  ✅ Created table: emails');

    // Create audit_logs table
    await db.execute(sql`
      CREATE TABLE audit_logs (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        user_id UUID REFERENCES users(id) ON DELETE SET NULL,
        action TEXT NOT NULL,
        resource TEXT NOT NULL,
        resource_id TEXT,
        old_value TEXT,
        new_value TEXT,
        ip_address TEXT,
        user_agent TEXT,
        success BOOLEAN NOT NULL DEFAULT true,
        error_message TEXT,
        created_at TIMESTAMP NOT NULL DEFAULT NOW()
      )
    `);
    logger.success('  ✅ Created table: audit_logs');

    // Create indexes
    logger.info('\n📊 Creating indexes...');

    await db.execute(sql`CREATE INDEX idx_user_email_accounts_user ON user_email_accounts(user_id)`);
    await db.execute(sql`CREATE INDEX idx_user_email_accounts_account ON user_email_accounts(email_account_id)`);
    await db.execute(sql`CREATE INDEX idx_contacts_account ON contacts(email_account_id)`);
    await db.execute(sql`CREATE INDEX idx_contacts_email ON contacts(email)`);
    await db.execute(sql`CREATE INDEX idx_emails_account ON emails(email_account_id)`);
    await db.execute(sql`CREATE INDEX idx_emails_contact ON emails(contact_id)`);
    await db.execute(sql`CREATE INDEX idx_emails_thread ON emails(thread_id)`);
    await db.execute(sql`CREATE INDEX idx_emails_date ON emails(date DESC)`);

    logger.success('  ✅ Created all indexes');

    logger.success('\n✅ Fresh database created successfully!');
    logger.info('\n📝 Next steps:');
    logger.info('   1. Run seed script to create admin user:');
    logger.info('      node src/scripts/seed-admin.js');
    logger.info('   2. Start the server:');
    logger.info('      npm run dev');

  } catch (error) {
    logger.error('❌ Failed to create fresh database:', error);
    throw error;
  }
}

// Run the script
freshDatabase()
  .then(() => {
    logger.success('🎉 Script completed!');
    process.exit(0);
  })
  .catch((error) => {
    logger.error('💥 Script failed:', error);
    process.exit(1);
  });
