-- Add is_archived column to letter_incoming_recipients if it doesn't exist
ALTER TABLE letter_incoming_recipients 
ADD COLUMN IF NOT EXISTS is_archived BOOLEAN DEFAULT FALSE;

-- Add is_archived column to letter_outgoing_recipients if it doesn't exist
ALTER TABLE letter_outgoing_recipients 
ADD COLUMN IF NOT EXISTS is_archived BOOLEAN DEFAULT FALSE;

-- Add indexes for efficient archiving queries on letter_incoming_recipients
-- Note: letter_incoming_recipients uses recipient_user_id and recipient_department_id
CREATE INDEX IF NOT EXISTS idx_letter_incoming_recipients_archived 
ON letter_incoming_recipients(is_archived, recipient_user_id, letter_id) 
WHERE is_archived = false;

CREATE INDEX IF NOT EXISTS idx_letter_incoming_recipients_user_archived 
ON letter_incoming_recipients(recipient_user_id, is_archived, letter_id);

CREATE INDEX IF NOT EXISTS idx_letter_incoming_recipients_letter_archived 
ON letter_incoming_recipients(letter_id, is_archived);

-- Add indexes for efficient archiving queries on letter_outgoing_recipients  
-- Note: letter_outgoing_recipients uses user_id and department_id
CREATE INDEX IF NOT EXISTS idx_letter_outgoing_recipients_archived 
ON letter_outgoing_recipients(is_archived, user_id, letter_id) 
WHERE is_archived = false;

CREATE INDEX IF NOT EXISTS idx_letter_outgoing_recipients_user_archived 
ON letter_outgoing_recipients(user_id, is_archived, letter_id);

CREATE INDEX IF NOT EXISTS idx_letter_outgoing_recipients_letter_archived 
ON letter_outgoing_recipients(letter_id, is_archived);

-- Add composite index for filtering non-archived letters by department
CREATE INDEX IF NOT EXISTS idx_letter_incoming_recipients_dept_archived 
ON letter_incoming_recipients(recipient_department_id, is_archived, letter_id) 
WHERE is_archived = false;