-- Migration: Create CRM share tokens table
-- Description: Allows generating secure shareable links for customers to view their leads

CREATE TABLE IF NOT EXISTS crm_share_tokens (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    customer_id UUID NOT NULL REFERENCES crm_customers(id) ON DELETE CASCADE,
    token VARCHAR(64) NOT NULL UNIQUE,
    expires_at TIMESTAMP,
    created_by UUID NOT NULL REFERENCES users(id),
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_crm_share_tokens_token ON crm_share_tokens(token);
CREATE INDEX idx_crm_share_tokens_customer_id ON crm_share_tokens(customer_id);
CREATE INDEX idx_crm_share_tokens_tenant_id ON crm_share_tokens(tenant_id);

COMMENT ON TABLE crm_share_tokens IS 'Tokens for sharing customer lead data externally';
COMMENT ON COLUMN crm_share_tokens.token IS 'Unique secure token for accessing shared data';
COMMENT ON COLUMN crm_share_tokens.expires_at IS 'Optional expiration date (NULL = never expires)';
