-- Fix Email Import Feature
-- Date: 2025-07-23
-- Description: Fix forwarder import issues and improve duplicate detection

USE whp;

-- Ensure email_forwarders table has consistent schema
-- Check if destination_type column exists and update if needed
-- Note: The production database may have different schemas, so we handle both cases

-- Add destination_type column if it doesn't exist
-- This is safe to run multiple times
SET @db_name = DATABASE();
SET @table_name = 'email_forwarders';
SET @column_exists = (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = @db_name 
    AND TABLE_NAME = @table_name 
    AND COLUMN_NAME = 'destination_type'
);

SET @sql = IF(@column_exists = 0,
    'ALTER TABLE email_forwarders ADD COLUMN destination_type ENUM(''email'', ''domain'') DEFAULT ''email'' AFTER destination_email',
    'SELECT ''Column destination_type already exists'' AS status'
);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Feature improvements summary:
-- 1. Fixed forwarder import to use 'email' instead of 'external' for destination_type
-- 2. Added dynamic column detection to handle different database schemas
-- 3. Improved duplicate checking for both email accounts and forwarders
-- 4. Enhanced import feedback with detailed results
-- 5. Better error handling and reporting