-- Tabela de clientes do CRM (multi-tenant)
CREATE TABLE IF NOT EXISTS crm_customers (
    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) NOT NULL,
    email VARCHAR(255),
    phone VARCHAR(50),
    company VARCHAR(255),
    position VARCHAR(100),
    
    -- Endereço
    address VARCHAR(255),
    city VARCHAR(100),
    state VARCHAR(50),
    zip_code VARCHAR(20),
    country VARCHAR(100) DEFAULT 'Brasil',
    
    -- Informações adicionais
    notes TEXT,
    tags TEXT[], -- Array de tags para filtros rápidos
    
    -- 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_email_per_tenant UNIQUE (tenant_id, email)
);

-- Tabela de listas para organizar clientes
CREATE TABLE IF NOT EXISTS crm_lists (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    
    name VARCHAR(100) NOT NULL,
    description TEXT,
    color VARCHAR(7) DEFAULT '#3b82f6', -- Hex color
    
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- Lista deve ter nome único por agência
    CONSTRAINT unique_list_per_tenant UNIQUE (tenant_id, name)
);

-- Relacionamento N:N entre clientes e listas
CREATE TABLE IF NOT EXISTS crm_customer_lists (
    customer_id UUID REFERENCES crm_customers(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 (customer_id, list_id)
);

-- Índices para performance
CREATE INDEX idx_crm_customers_tenant_id ON crm_customers(tenant_id);
CREATE INDEX idx_crm_customers_email ON crm_customers(email);
CREATE INDEX idx_crm_customers_name ON crm_customers(name);
CREATE INDEX idx_crm_customers_is_active ON crm_customers(is_active);
CREATE INDEX idx_crm_customers_tags ON crm_customers USING GIN(tags);

CREATE INDEX idx_crm_lists_tenant_id ON crm_lists(tenant_id);
CREATE INDEX idx_crm_lists_name ON crm_lists(name);

CREATE INDEX idx_crm_customer_lists_customer_id ON crm_customer_lists(customer_id);
CREATE INDEX idx_crm_customer_lists_list_id ON crm_customer_lists(list_id);

-- Trigger para atualizar updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

CREATE TRIGGER update_crm_customers_updated_at BEFORE UPDATE ON crm_customers
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_crm_lists_updated_at BEFORE UPDATE ON crm_lists
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
