-- Migration: Support Multiple Email Providers
-- This migration allows storing multiple provider configurations per channel type
-- Previously: Only one config per channel_type (unique constraint)
-- Now: Multiple configs per channel_type, identified by provider

-- Step 1: Drop the unique constraint on channel_type
ALTER TABLE notification_delivery_config
DROP INDEX channel_type;

-- Step 2: Add unique constraint on (channel_type, provider) combination
ALTER TABLE notification_delivery_config
ADD UNIQUE KEY unique_channel_provider (channel_type, provider);

-- Step 3: Add active_provider column to track which provider is currently active
ALTER TABLE notification_delivery_config
ADD COLUMN is_active BOOLEAN DEFAULT false AFTER is_enabled;

-- Step 4: Set current email config as active (if exists)
UPDATE notification_delivery_config
SET is_active = true
WHERE channel_type = 'email'
  AND is_enabled = true
LIMIT 1;

-- Step 5: Insert Mailtrap configuration if not exists
INSERT IGNORE INTO notification_delivery_config
(channel_type, is_enabled, is_active, provider, provider_config, status, success_rate, created_by, updated_by, created_at, updated_at)
VALUES (
  'email',
  false,
  false,
  'Mailtrap',
  JSON_OBJECT(
    'host', 'live.smtp.mailtrap.io',
    'port', 587,
    'secure', false,
    'user', 'apismtp@mailtrap.io',
    'pass', '',
    'senderEmail', '',
    'senderName', ''
  ),
  'Not Configured',
  0.0,
  1,
  1,
  NOW(),
  NOW()
);

-- Step 6: Insert AWS SES configuration if not exists
INSERT IGNORE INTO notification_delivery_config
(channel_type, is_enabled, is_active, provider, provider_config, status, success_rate, created_by, updated_by, created_at, updated_at)
VALUES (
  'email',
  false,
  false,
  'AWS SES',
  JSON_OBJECT(
    'host', '',
    'port', 587,
    'secure', false,
    'user', '',
    'pass', '',
    'senderEmail', '',
    'senderName', '',
    'region', 'us-east-1',
    'configurationSet', ''
  ),
  'Not Configured',
  0.0,
  1,
  1,
  NOW(),
  NOW()
);

-- Verify the migration
SELECT
  id,
  channel_type,
  provider,
  is_enabled,
  is_active,
  status,
  JSON_EXTRACT(provider_config, '$.host') as smtp_host,
  created_at,
  updated_at
FROM notification_delivery_config
WHERE channel_type = 'email'
ORDER BY provider;
