-- Migration: Create CRM funnels and stages
-- Description: Allows agencies to create custom lead monitoring pipelines

CREATE TABLE IF NOT EXISTS crm_funnels (
    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,
    is_default BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    CONSTRAINT unique_funnel_per_tenant UNIQUE (tenant_id, name)
);

CREATE TABLE IF NOT EXISTS crm_funnel_stages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    funnel_id UUID NOT NULL REFERENCES crm_funnels(id) ON DELETE CASCADE,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    color VARCHAR(7) DEFAULT '#3b82f6',
    order_index INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Add funnel and stage to leads
ALTER TABLE crm_leads 
ADD COLUMN funnel_id UUID REFERENCES crm_funnels(id) ON DELETE SET NULL,
ADD COLUMN stage_id UUID REFERENCES crm_funnel_stages(id) ON DELETE SET NULL;

-- Indices
CREATE INDEX idx_crm_funnels_tenant_id ON crm_funnels(tenant_id);
CREATE INDEX idx_crm_funnel_stages_funnel_id ON crm_funnel_stages(funnel_id);
CREATE INDEX idx_crm_leads_funnel_id ON crm_leads(funnel_id);
CREATE INDEX idx_crm_leads_stage_id ON crm_leads(stage_id);

-- Triggers for updated_at
CREATE TRIGGER update_crm_funnels_updated_at BEFORE UPDATE ON crm_funnels
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_crm_funnel_stages_updated_at BEFORE UPDATE ON crm_funnel_stages
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Function to create default funnel for a tenant
CREATE OR REPLACE FUNCTION create_default_crm_funnel(t_id UUID)
RETURNS UUID AS $$
DECLARE
    f_id UUID;
BEGIN
    INSERT INTO crm_funnels (tenant_id, name, description, is_default)
    VALUES (t_id, 'Funil de Vendas Padrão', 'Monitoramento básico de leads', true)
    RETURNING id INTO f_id;

    INSERT INTO crm_funnel_stages (funnel_id, name, color, order_index) VALUES
    (f_id, 'Novo', '#3b82f6', 0),
    (f_id, 'Qualificado', '#10b981', 1),
    (f_id, 'Proposta', '#f59e0b', 2),
    (f_id, 'Negociação', '#8b5cf6', 3),
    (f_id, 'Fechado', '#10b981', 4),
    (f_id, 'Perdido', '#ef4444', 5);

    RETURN f_id;
END;
$$ LANGUAGE plpgsql;
