import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  try {
    // Check if columns already exist (for idempotency and backward compatibility)
    const tableDescription = await queryInterface.describeTable('workflow_requests');
    
    // 1. Add workflow_type column to workflow_requests (only if it doesn't exist)
    if (!tableDescription.workflow_type) {
      try {
        await queryInterface.addColumn('workflow_requests', 'workflow_type', {
          type: DataTypes.STRING(50),
          allowNull: true,
          defaultValue: 'NON_TEMPLATIZED'
        });
        console.log('✅ Added workflow_type column');
      } catch (error: any) {
        // Column might have been added manually, check if it exists now
        const updatedDescription = await queryInterface.describeTable('workflow_requests');
        if (!updatedDescription.workflow_type) {
          throw error; // Re-throw if column still doesn't exist
        }
        console.log('Note: workflow_type column already exists (may have been added manually)');
      }
    } else {
      console.log('Note: workflow_type column already exists, skipping');
    }

    // 2. Add template_id column (nullable, for admin templates)
    // Note: Foreign key constraint will be added later if workflow_templates table exists
    if (!tableDescription.template_id) {
      try {
        await queryInterface.addColumn('workflow_requests', 'template_id', {
          type: DataTypes.UUID,
          allowNull: true
        });
        console.log('✅ Added template_id column');
      } catch (error: any) {
        // Column might have been added manually, check if it exists now
        const updatedDescription = await queryInterface.describeTable('workflow_requests');
        if (!updatedDescription.template_id) {
          throw error; // Re-throw if column still doesn't exist
        }
        console.log('Note: template_id column already exists (may have been added manually)');
      }
    } else {
      console.log('Note: template_id column already exists, skipping');
    }

    // Get updated table description for index creation
    const finalTableDescription = await queryInterface.describeTable('workflow_requests');

    // 3. Create index for workflow_type (only if column exists)
    if (finalTableDescription.workflow_type) {
      try {
        await queryInterface.addIndex('workflow_requests', ['workflow_type'], {
          name: 'idx_workflow_requests_workflow_type'
        });
        console.log('✅ Created workflow_type index');
      } catch (error: any) {
        // Index might already exist, ignore error
        if (error.message?.includes('already exists') || error.message?.includes('duplicate')) {
          console.log('Note: workflow_type index already exists');
        } else {
          console.log('Note: Could not create workflow_type index:', error.message);
        }
      }
    }

    // 4. Create index for template_id (only if column exists)
    if (finalTableDescription.template_id) {
      try {
        await queryInterface.addIndex('workflow_requests', ['template_id'], {
          name: 'idx_workflow_requests_template_id'
        });
        console.log('✅ Created template_id index');
      } catch (error: any) {
        // Index might already exist, ignore error
        if (error.message?.includes('already exists') || error.message?.includes('duplicate')) {
          console.log('Note: template_id index already exists');
        } else {
          console.log('Note: Could not create template_id index:', error.message);
        }
      }
    }

    // 5. Update existing records to have workflow_type (if any exist and column exists)
    if (finalTableDescription.workflow_type) {
      try {
        const [result] = await queryInterface.sequelize.query(`
          UPDATE workflow_requests 
          SET workflow_type = 'NON_TEMPLATIZED' 
          WHERE workflow_type IS NULL;
        `);
        console.log('✅ Updated existing records with workflow_type');
      } catch (error: any) {
        // Ignore if table is empty or other error
        console.log('Note: Could not update existing records:', error.message);
      }
    }
  } catch (error: any) {
    console.error('Migration error:', error.message);
    throw error;
  }
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  // Remove indexes
  await queryInterface.removeIndex('workflow_requests', 'idx_workflow_requests_template_id');
  await queryInterface.removeIndex('workflow_requests', 'idx_workflow_requests_workflow_type');

  // Remove columns
  await queryInterface.removeColumn('workflow_requests', 'template_id');
  await queryInterface.removeColumn('workflow_requests', 'workflow_type');
}

