-- Migration: Add import_method tracking to email_messages
-- Purpose: Track how emails were imported (IMAP, Graph API, or manual upload)
-- Date: 2026-01-06

-- Add import_method column
ALTER TABLE email_messages 
ADD COLUMN IF NOT EXISTS import_method VARCHAR(50) DEFAULT 'imap';

-- Add comment
COMMENT ON COLUMN email_messages.import_method IS 'How the email was imported: imap, graph_api, or manual_upload';

-- Create index for filtering by import method
CREATE INDEX IF NOT EXISTS idx_email_messages_import_method ON email_messages(import_method);

-- Update existing records to reflect their actual source
-- (all existing emails were fetched via IMAP or Graph API)
UPDATE email_messages 
SET import_method = 'imap' 
WHERE import_method IS NULL;

-- Add constraint to ensure valid values
ALTER TABLE email_messages
DROP CONSTRAINT IF EXISTS chk_email_import_method;

ALTER TABLE email_messages
ADD CONSTRAINT chk_email_import_method
CHECK (import_method IN ('imap', 'graph_api', 'manual_upload'));
