CREATE TABLE IF NOT EXISTS pipeline_opportunity_emails (
    opportunity_id INTEGER REFERENCES pipeline_opportunities(id) ON DELETE CASCADE,
    email_id INTEGER REFERENCES email_messages(id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    PRIMARY KEY (opportunity_id, email_id)
);

INSERT INTO pipeline_opportunity_emails (opportunity_id, email_id)
SELECT id, email_id FROM pipeline_opportunities WHERE email_id IS NOT NULL 
ON CONFLICT DO NOTHING;
