-- Tabela de leads do CRM (multi-tenant)
CREATE TABLE IF NOT EXISTS crm_leads (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,

    -- Dados básicos
    name VARCHAR(255),
    email VARCHAR(255),
    phone VARCHAR(50),

    -- Origem do lead
    source VARCHAR(50) DEFAULT 'import',
    source_meta JSONB DEFAULT '{}'::jsonb,

    -- Status
    status VARCHAR(50) DEFAULT 'novo',

    -- Informações adicionais
    notes TEXT,
    tags TEXT[],

    -- Controle
    is_active BOOLEAN DEFAULT true,
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    -- Constraint: email deve ser único por agência (pode repetir entre agências)
    CONSTRAINT unique_lead_email_per_tenant UNIQUE (tenant_id, email)
);

-- Relacionamento N:N entre leads e listas
CREATE TABLE IF NOT EXISTS crm_lead_lists (
    lead_id UUID REFERENCES crm_leads(id) ON DELETE CASCADE,
    list_id UUID REFERENCES crm_lists(id) ON DELETE CASCADE,
    added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    added_by UUID REFERENCES users(id),
    PRIMARY KEY (lead_id, list_id)
);

-- Índices para performance
CREATE INDEX IF NOT EXISTS idx_crm_leads_tenant_id ON crm_leads(tenant_id);
CREATE INDEX IF NOT EXISTS idx_crm_leads_email ON crm_leads(email);
CREATE INDEX IF NOT EXISTS idx_crm_leads_phone ON crm_leads(phone);
CREATE INDEX IF NOT EXISTS idx_crm_leads_status ON crm_leads(status);
CREATE INDEX IF NOT EXISTS idx_crm_leads_is_active ON crm_leads(is_active);
CREATE INDEX IF NOT EXISTS idx_crm_leads_tags ON crm_leads USING GIN(tags);
CREATE INDEX IF NOT EXISTS idx_crm_leads_source ON crm_leads(source);

CREATE INDEX IF NOT EXISTS idx_crm_lead_lists_lead_id ON crm_lead_lists(lead_id);
CREATE INDEX IF NOT EXISTS idx_crm_lead_lists_list_id ON crm_lead_lists(list_id);

-- Trigger para atualizar updated_at (usa a função update_updated_at_column criada em 014_create_crm_tables.sql)
DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM pg_proc
        WHERE proname = 'update_updated_at_column'
    ) THEN
        IF NOT EXISTS (
            SELECT 1
            FROM pg_trigger
            WHERE tgname = 'update_crm_leads_updated_at'
        ) THEN
            CREATE TRIGGER update_crm_leads_updated_at BEFORE UPDATE ON crm_leads
                FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
        END IF;
    END IF;
END $$;
