-- Migration 170: Trusted sender-domain to customer mappings for email triage
-- Created: 2026-04-12

CREATE TABLE IF NOT EXISTS email_domain_customer_mappings (
    domain VARCHAR(255) PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
    source VARCHAR(50) NOT NULL DEFAULT 'manual',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_email_domain_customer_mappings_customer_id
ON email_domain_customer_mappings(customer_id);

CREATE INDEX IF NOT EXISTS idx_email_domain_customer_mappings_source
ON email_domain_customer_mappings(source);

CREATE OR REPLACE FUNCTION update_email_domain_customer_mappings_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trigger_email_domain_customer_mappings_updated_at ON email_domain_customer_mappings;
CREATE TRIGGER trigger_email_domain_customer_mappings_updated_at
    BEFORE UPDATE ON email_domain_customer_mappings
    FOR EACH ROW
    EXECUTE FUNCTION update_email_domain_customer_mappings_updated_at();

COMMENT ON TABLE email_domain_customer_mappings IS 'Trusted mappings from sender email domain to customer for fast auto-linking in email triage';
COMMENT ON COLUMN email_domain_customer_mappings.source IS 'manual, auto_link, import, etc.';
