-- Migration: Create signup_templates table
-- Descrição: Tabela para armazenar templates personalizados de cadastro

CREATE TABLE IF NOT EXISTS signup_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    description TEXT,
    slug VARCHAR(100) UNIQUE NOT NULL,
    
    -- Campos do formulário (JSON com array de campos)
    form_fields JSONB NOT NULL DEFAULT '[]'::jsonb,
    
    -- Módulos habilitados (JSON com array de módulos)
    enabled_modules JSONB NOT NULL DEFAULT '[]'::jsonb,
    
    -- Configurações adicionais
    redirect_url VARCHAR(500),
    success_message TEXT,
    
    -- Branding
    custom_logo_url VARCHAR(500),
    custom_primary_color VARCHAR(20),
    
    -- Controle
    is_active BOOLEAN DEFAULT true,
    usage_count INTEGER DEFAULT 0,
    
    -- Auditoria
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Índices para performance
CREATE INDEX idx_signup_templates_slug ON signup_templates(slug);
CREATE INDEX idx_signup_templates_is_active ON signup_templates(is_active);
CREATE INDEX idx_signup_templates_created_by ON signup_templates(created_by);

-- Comentários
COMMENT ON TABLE signup_templates IS 'Templates personalizados para links de cadastro';
COMMENT ON COLUMN signup_templates.form_fields IS 'Array JSON com campos do formulário: [{"name": "email", "required": true, "type": "email"}]';
COMMENT ON COLUMN signup_templates.enabled_modules IS 'Array JSON com módulos habilitados: ["CRM", "ERP", "PROJECTS"]';
COMMENT ON COLUMN signup_templates.slug IS 'Slug único usado na URL: aggios.app/cadastro/{slug}';

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

CREATE TRIGGER trigger_update_signup_templates_updated_at
    BEFORE UPDATE ON signup_templates
    FOR EACH ROW
    EXECUTE FUNCTION update_signup_templates_updated_at();

-- Template padrão (exemplo)
INSERT INTO signup_templates (name, description, slug, form_fields, enabled_modules) VALUES
('Cadastro Rápido CRM', 'Template simplificado apenas com CRM', 'crm-rapido', 
 '[
    {"name": "email", "label": "E-mail", "type": "email", "required": true, "order": 1},
    {"name": "password", "label": "Senha", "type": "password", "required": true, "order": 2},
    {"name": "subdomain", "label": "Subdomínio", "type": "text", "required": true, "order": 3},
    {"name": "company_name", "label": "Nome da Empresa", "type": "text", "required": false, "order": 4}
 ]'::jsonb,
 '["CRM"]'::jsonb
);
