from django.core.management.base import BaseCommand
from django.db import connections, transaction
from api.models import *
from django.conf import settings
from django.utils import timezone
import pytz
from django.apps import apps
import pymysql
import time

import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Define the file path for the log file
log_file = f'{settings.BASE_DIR}/logs/sync_data.log'

# Create a file handler and set its properties
file_handler = RotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=5)
file_handler.setLevel(logging.INFO)

# Define the log format
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)

# Add the file handler to the logger
logger.addHandler(file_handler)


class Command(BaseCommand):
    help = 'Synchronizes opportunities data from the source database'

    missing_value = "Não Informado"

    def handle(self, *args, **options): 
        # Assuming 'default' is your target database and 'source_db' is your source database alias in settings.py
        self.stdout.write(self.style.SUCCESS('Starting synchronization process...'))

        try:
            start_time = time.time()
            # Step 1: Truncate the tables:
            # - bi_acessos
            # - bi_acoes_funil
            # - bi_atividades
            # - bi_oportunidades
            # - bi_propostas
            # - bi_vendas
            self.truncate_table()
            
            # Step 2: Fetch data from the source_db
            self.sync_data()
            
            # Step 3: Create the star schema using MySQL Views
            #self.create_star_schema()
            
            total_time = round((time.time() - start_time),2)
            
            self.stdout.write(self.style.SUCCESS('Synchronization process completed successfully. Total time: ' + str(total_time) + ' seconds.'))
            logger.info('Synchronization process completed successfully. Total time: ' + str(total_time) + ' seconds.')
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Synchronization process failed: {e}'))
            logger.error(f'Synchronization process failed: {e}')

    
    def truncate_table(self):
        with transaction.atomic():
            with connections['mysql'].cursor() as cursor:
                tables_to_truncate = [
                    'bi_acessos',
                    'bi_acoes_funil',
                    'bi_atividades',
                    'bi_oportunidades',
                    'bi_propostas',
                    'bi_vendas',
                    'bi_utms',
                ]

                self.stdout.write(self.style.NOTICE('Truncating tables...'))
                logger.info('Truncating tables...')
                try:
                    with connections['mysql'].cursor() as cursor:
                        for table in tables_to_truncate:
                            try:
                                self.stdout.write(self.style.NOTICE(f'Truncating table {table}...'))
                                logger.info(f'Truncating table {table}...')
                                cursor.execute(f"TRUNCATE TABLE {table}")
                            except Exception as e:
                                self.stdout.write(self.style.ERROR(f'Error truncating table {table}: {e}'))
                                logger.error(f'Error truncating table {table}: {e}')
                                raise e
                except Exception as e:
                    self.stdout.write(self.style.ERROR(f'Error truncating tables: {e}'))
                    logger.error(f'Error truncating tables: {e}')
                    raise e
   
        self.stdout.write(self.style.SUCCESS('Truncation completed.'))
        logger.info('Truncation completed.')
 
    
    def sync_data(self):
        self.stdout.write(self.style.NOTICE('Fetching data from source database...'))
        logger.info('Fetching data from source database...')

        # Choose the correct connection based on DEBUG setting
        #connection_name = 'source_db_development' if settings.DEBUG else 'source_db_production'
        connection_name = 'source_db'
        source_connection = connections[connection_name]

        # Create a dictionary to map source tables to target tables
        table_mapping = {
            'vw_pixcrm_argo_acessos': 'bi_acessos',
            'vw_pixcrm_argo_acoes_funil': 'bi_acoes_funil',
            'vw_pixcrm_argo_atividades': 'bi_atividades',
            'vw_pixcrm_argo_oportunidades': 'bi_oportunidades',
            'vw_pixcrm_argo_propostas': 'bi_propostas',
            'vw_pixcrm_argo_vendas': 'bi_vendas',
            'vw_pixcrm_argo_utms': 'bi_utms'
        }

        try:
            ### Limiting transfer if DEBUG True
            if settings.DEBUG:
                limit = 100
            else:
                limit = None
            with source_connection.cursor() as source_cursor:
                for source_table, target_table in table_mapping.items():
                    source_cursor.execute(f"SELECT * FROM {source_table} {'LIMIT ' + str(limit) if limit is not None else ''}")
                    columns = [col[0] for col in source_cursor.description]

                    rows_to_create = []
                    for row in source_cursor.fetchall():
                        processed_row = {
                            col: ("Não Informado" if (value is None or value == "") and isinstance(value, str) else
                                   0 if (value is None or value == "") and isinstance(value, (int, float)) else
                                   value)
                            for col, value in zip(columns, row)
                        }
                        for field, value in processed_row.items():
                            if (value is None or value == "" or value == "Não informada") and isinstance(value, str):
                                processed_row[field] = self.missing_value
                        rows_to_create.append(processed_row)

                    with connections['mysql'].cursor() as target_cursor:
                        for row in rows_to_create:
                            placeholders = ', '.join(['%s'] * len(row))
                            columns = ', '.join(row.keys())
                            values = tuple(row.values())
                            target_cursor.execute(f"INSERT INTO {target_table} ({columns}) VALUES ({placeholders})", values)

            self.stdout.write(self.style.SUCCESS('Data fetched and processed. Records inserted into target tables.'))
            logger.info('Data fetched and processed. Records inserted into target tables.')
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error fetching and processing data: {e}'))
            logger.error(f'Error fetching and processing data: {e}')
            raise e
    
    def create_star_schema(self):
        # Create the star schema
        # Create the fact table
        # Create the dimension tables

        sql = """

                CREATE VIEW IF NOT EXISTS  `vw_bi_oportunidades`  AS SELECT `bi_oportunidades`.`oportunidade_id` AS `oportunidade_id`, `bi_oportunidades`.`nome` AS `nome`, `bi_oportunidades`.`data` AS `data`, CASE WHEN `bi_oportunidades`.`consultor` in ('Não informado','Não Informado','Não informada','Não Informada',NULL,'') THEN 'Não Informado' WHEN `bi_oportunidades`.`consultor` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`consultor` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`consultor` END AS `consultor`, CASE WHEN `bi_oportunidades`.`cidade` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`cidade` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`cidade` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`cidade` END AS `cidade`, CASE WHEN `bi_oportunidades`.`estado` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`estado` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`estado` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`estado` END AS `estado`, CASE WHEN `bi_oportunidades`.`estado_civil` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`estado_civil` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`estado_civil` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`estado_civil` END AS `estado_civil`, CASE WHEN `bi_oportunidades`.`profissao` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`profissao` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`profissao` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`profissao` END AS `profissao`, CASE WHEN `bi_oportunidades`.`sexo` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`sexo` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`sexo` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`sexo` END AS `sexo`, CASE WHEN `bi_oportunidades`.`renda` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`renda` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`renda` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`renda` END AS `renda`, CASE WHEN `bi_oportunidades`.`idade` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`idade` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`idade` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`idade` END AS `idade`, CASE WHEN `bi_oportunidades`.`idade_range` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`idade_range` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`idade_range` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`idade_range` END AS `idade_range`, CASE WHEN `bi_oportunidades`.`midia` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`midia` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`midia` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`midia` END AS `midia`, CASE WHEN `bi_oportunidades`.`canal` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`canal` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`canal` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`canal` END AS `canal`, CASE WHEN `bi_oportunidades`.`temperatura` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`temperatura` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`temperatura` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`temperatura` END AS `temperatura`, CASE WHEN `bi_oportunidades`.`unidade` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`unidade` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`unidade` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`unidade` END AS `unidade`, CASE WHEN `bi_oportunidades`.`interesse` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`interesse` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`interesse` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`interesse` END AS `interesse`, CASE WHEN `bi_oportunidades`.`categoria` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`categoria` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`categoria` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`categoria` END AS `categoria`, CASE WHEN `bi_oportunidades`.`tipo` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`tipo` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`tipo` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`tipo` END AS `tipo`, CASE WHEN `bi_oportunidades`.`status` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`status` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`status` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`status` END AS `status`, CASE WHEN `bi_oportunidades`.`etapa_funil` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`etapa_funil` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`etapa_funil` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`etapa_funil` END AS `etapa_funil`, `bi_oportunidades`.`ordem_funil` AS `ordem_funil`, CASE WHEN `bi_oportunidades`.`empreendimento` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`empreendimento` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`empreendimento` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`empreendimento` END AS `empreendimento`, CASE WHEN `bi_oportunidades`.`motivo_perda_pausa` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`motivo_perda_pausa` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`motivo_perda_pausa` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`motivo_perda_pausa` END AS `motivo_perda_pausa`, `bi_oportunidades`.`data_finalizacao` AS `data_finalizacao`, `bi_oportunidades`.`dias_finalizacao` AS `dias_finalizacao`, CASE WHEN `bi_oportunidades`.`finalizacao_range` in ('Não informado','Não Informado','Não informada','Não Informada') THEN 'Não Informado' WHEN `bi_oportunidades`.`finalizacao_range` is null THEN 'Não Informado' WHEN `bi_oportunidades`.`finalizacao_range` = '' THEN 'Não Informado' ELSE `bi_oportunidades`.`finalizacao_range` END AS `finalizacao_range` FROM `bi_oportunidades` ;

                DROP VIEW IF EXISTS `dCanais`;
                DROP TABLE IF EXISTS `dCanais`;
                CREATE TABLE IF NOT EXISTS  `dCanais`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`canal` AS `canal` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`canal` is null,'Não Informado',`Base`.`canal`)) AS `canal_id`, if(`Base`.`canal` is null,'Não Informado',`Base`.`canal`) AS `canal` FROM `Base` ;
               
                DROP VIEW IF EXISTS `dCategorias`;
                DROP TABLE IF EXISTS `dCategorias`;
                CREATE TABLE IF NOT EXISTS  `dCategorias`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`categoria` AS `categoria` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`categoria` is null,'Não Informado',`Base`.`categoria`)) AS `categoria_id`, if(`Base`.`categoria` is null,'Não Informado',`Base`.`categoria`) AS `categoria` FROM `Base`  ;

                DROP VIEW IF EXISTS `dConsultores`;
                DROP TABLE IF EXISTS `dConsultores`;
                CREATE TABLE IF NOT EXISTS  `dConsultores`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`consultor` AS `consultor` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by `Base`.`consultor`) AS `consultor_id`, `Base`.`consultor` AS `consultor` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dEmpreendimentos`;
                DROP TABLE IF EXISTS `dEmpreendimentos`;
                CREATE TABLE IF NOT EXISTS  `dEmpreendimentos`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`empreendimento` AS `empreendimento` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(1 is null,'Não Informado',`Base`.`empreendimento`)) AS `empreendimento_id`, if(1 is null,'Não Informado',`Base`.`empreendimento`) AS `empreendimento` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dEstados`;
                DROP TABLE IF EXISTS `dEstadosCivis`;
                CREATE TABLE IF NOT EXISTS  `dEstadosCivis`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`estado_civil` AS `estado_civil` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`estado_civil` is null,'Não Informado',`Base`.`estado_civil`)) AS `estado_civil_id`, if(`Base`.`estado_civil` is null,'Não Informado',`Base`.`estado_civil`) AS `estado_civil` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dEtapasFunil`;
                DROP TABLE IF EXISTS `dEtapasFunil`;
                CREATE TABLE IF NOT EXISTS  `dEtapasFunil`  AS SELECT DISTINCT `vw_bi_oportunidades`.`etapa_funil` AS `etapa_funil`, `vw_bi_oportunidades`.`ordem_funil` AS `funil_id`, concat(`vw_bi_oportunidades`.`ordem_funil`,' - ',`vw_bi_oportunidades`.`etapa_funil`) AS `etapa` FROM `vw_bi_oportunidades` ;
                
                DROP VIEW IF EXISTS `dFaixasIdade`;
                DROP TABLE IF EXISTS `dFaixasIdade`;
                CREATE TABLE IF NOT EXISTS  `dFaixasIdade`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`idade_range` AS `idade_range` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`idade_range` is null,'Não Informado',`Base`.`idade_range`)) AS `idade_range_id`, if(`Base`.`idade_range` is null,'Não Informado',`Base`.`idade_range`) AS `idade_range` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dFechamentoDias`;
                DROP TABLE IF EXISTS `dFechamentoDias`;
                CREATE TABLE IF NOT EXISTS  `dFechamentoDias`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`finalizacao_range` AS `finalizacao_range` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`finalizacao_range` is null,'Não Informado',`Base`.`finalizacao_range`)) AS `fechamento_id`, if(`Base`.`finalizacao_range` is null,'Não Informado',`Base`.`finalizacao_range`) AS `finalizacao_range` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dInteresses`;
                DROP TABLE IF EXISTS `dInteresses`;
                CREATE TABLE IF NOT EXISTS  `dInteresses`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`interesse` AS `interesse` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by `Base`.`interesse`) AS `interesse_id`, if(`Base`.`interesse` is null,'Não Informada',`Base`.`interesse`) AS `interesse` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dMidias`;
                DROP TABLE IF EXISTS `dMidias`;
                CREATE TABLE IF NOT EXISTS  `dMidias`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`midia` AS `midia` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`midia` is null,'Não Informado',`Base`.`midia`)) AS `midia_id`, if(`Base`.`midia` is null,'Não Informado',`Base`.`midia`) AS `midia` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dMotivosPerdaPausa`;
                DROP TABLE IF EXISTS `dMotivosPerdaPausa`;
                CREATE TABLE IF NOT EXISTS  `dMotivosPerdaPausa`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`motivo_perda_pausa` AS `motivo_perda_pausa` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`motivo_perda_pausa` is null,'Não Informado',`Base`.`motivo_perda_pausa`)) AS `motivo_id`, if(`Base`.`motivo_perda_pausa` is null,'Não Informado',`Base`.`motivo_perda_pausa`) AS `motivo_perda_pausa` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dProfissoes`;
                DROP TABLE IF EXISTS `dProfissoes`;
                CREATE TABLE IF NOT EXISTS  `dProfissoes`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`profissao` AS `profissao` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`profissao` is null,'Não Informado',`Base`.`profissao`)) AS `profissao_id`, if(`Base`.`profissao` is null,'Não Informado',`Base`.`profissao`) AS `profissao` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dQuartos`;
                DROP TABLE IF EXISTS `dQuartos`;
                CREATE TABLE IF NOT EXISTS  `dQuartos`  AS WITH Base AS (SELECT DISTINCT `bi_vendas`.`quartos` AS `quartos` FROM `bi_vendas`) SELECT row_number() over ( order by if(`Base`.`quartos` is null,'Não Informado',`Base`.`quartos`)) AS `quartos_id`, if(`Base`.`quartos` is null,'Não Informado',`Base`.`quartos`) AS `quartos` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dRegioes`;
                DROP TABLE IF EXISTS `dRegioes`;
                CREATE TABLE IF NOT EXISTS  `dRegioes`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`cidade` AS `cidade`, `vw_bi_oportunidades`.`estado` AS `estado` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`cidade` is null,'Não Informado',`Base`.`cidade`),if(`Base`.`estado` is null,'Não Informado',`Base`.`estado`)) AS `regiao_id`, if(`Base`.`cidade` is null,'Não Informado',`Base`.`cidade`) AS `cidade`, if(`Base`.`estado` is null,'Não Informado',`Base`.`estado`) AS `estado` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dRendas`;
                DROP TABLE IF EXISTS `dRendas`;
                CREATE TABLE IF NOT EXISTS  `dRendas`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`renda` AS `renda` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`renda` is null,'Não Informado',`Base`.`renda`)) AS `renda_id`, if(`Base`.`renda` is null,'Não Informado',`Base`.`renda`) AS `renda` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dSexos`;
                DROP TABLE IF EXISTS `dSexos`;
                CREATE TABLE IF NOT EXISTS  `dSexos`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`sexo` AS `sexo` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`sexo` is null,'Não Informado',`Base`.`sexo`)) AS `sexo_id`, if(`Base`.`sexo` is null,'Não Informado',`Base`.`sexo`) AS `sexo` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dStatus`;
                DROP TABLE IF EXISTS `dStatus`;
                CREATE TABLE IF NOT EXISTS  `dStatus`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`status` AS `status` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(1 is null,'Não Informado',`Base`.`status`)) AS `status_id`, if(1 is null,'Não Informado',`Base`.`status`) AS `status` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dStatusAtividade`;
                DROP TABLE IF EXISTS `dStatusAtividade`;
                CREATE TABLE IF NOT EXISTS  `dStatusAtividade`  AS WITH Base AS (SELECT DISTINCT `bi_atividades`.`status` AS `status` FROM `bi_atividades`) SELECT row_number() over ( order by `Base`.`status`) AS `status_atividade_id`, if(`Base`.`status` is null,'Não Informado',`Base`.`status`) AS `status_atividade` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dStatusProposta`;
                DROP TABLE IF EXISTS `dStatusProposta`;
                CREATE TABLE IF NOT EXISTS  `dStatusProposta`  AS WITH Base AS (SELECT DISTINCT `bi_propostas`.`status_proposta` AS `status_proposta` FROM `bi_propostas`) SELECT row_number() over ( order by if(`Base`.`status_proposta` is null,'Não Informado',`Base`.`status_proposta`)) AS `status_proposta_id`, if(`Base`.`status_proposta` is null,'Não Informado',`Base`.`status_proposta`) AS `status_proposta` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dSuites`;
                DROP TABLE IF EXISTS `dSuites`;
                CREATE TABLE IF NOT EXISTS  `dSuites`  AS WITH Base AS (SELECT DISTINCT `bi_vendas`.`suites` AS `suites` FROM `bi_vendas`) SELECT row_number() over ( order by if(`Base`.`suites` is null,'Não Informado',`Base`.`suites`)) AS `suites_id`, if(`Base`.`suites` is null,'Não Informado',`Base`.`suites`) AS `suites` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dTemperaturas`;
                DROP TABLE IF EXISTS `dTemperaturas`;
                CREATE TABLE IF NOT EXISTS  `dTemperaturas`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`temperatura` AS `temperatura` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`temperatura` is null,'Não Informado',`Base`.`temperatura`)) AS `temperatura_id`, if(`Base`.`temperatura` is null,'Não Informado',`Base`.`temperatura`) AS `temperatura` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dTipos`;
                DROP TABLE IF EXISTS `dTipos`;
                CREATE TABLE IF NOT EXISTS  `dTipos`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`tipo` AS `tipo` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(1 is null,'Não Informado',`Base`.`tipo`)) AS `tipo_id`, if(1 is null,'Não Informado',`Base`.`tipo`) AS `tipo` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dTiposAtividade`;
                DROP TABLE IF EXISTS `dTiposAtividade`;
                CREATE TABLE IF NOT EXISTS  `dTiposAtividade`  AS WITH Base AS (SELECT DISTINCT `bi_atividades`.`tipo` AS `tipo` FROM `bi_atividades`) SELECT row_number() over ( order by `Base`.`tipo`) AS `tipo_atividade_id`, if(`Base`.`tipo` is null,'Não Informado',`Base`.`tipo`) AS `tipo_atividade` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dTiposProposta`;
                DROP TABLE IF EXISTS `dTiposProposta`;
                CREATE TABLE IF NOT EXISTS  `dUnidades`  AS WITH Base AS (SELECT DISTINCT `vw_bi_oportunidades`.`unidade` AS `unidade` FROM `vw_bi_oportunidades`) SELECT row_number() over ( order by if(`Base`.`unidade` is null,'Não Informado',`Base`.`unidade`)) AS `unidade_id`, if(`Base`.`unidade` is null,'Não Informado',`Base`.`unidade`) AS `unidade` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dUnidadesEmpreendimento`;
                DROP TABLE IF EXISTS `dUnidadesEmpreendimento`;
                CREATE TABLE IF NOT EXISTS  `dUnidadesEmpreendimento`  AS WITH Base AS (SELECT DISTINCT `bi_propostas`.`empreendimento` AS `empreendimento`, `bi_propostas`.`unidade` AS `unidade` FROM `bi_propostas`) SELECT row_number() over ( order by if(`Base`.`empreendimento` is null,'Não Informado',`Base`.`empreendimento`),if(`Base`.`unidade` is null,'Não Informado',`Base`.`unidade`)) AS `unidade_empreendimento_id`, if(`Base`.`empreendimento` is null,'Não Informado',`Base`.`empreendimento`) AS `empreendimento`, if(`Base`.`unidade` is null,'Não Informado',`Base`.`unidade`) AS `unidade` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dVagas`;
                DROP TABLE IF EXISTS `dVagas`;
                CREATE TABLE IF NOT EXISTS  `dVagas`  AS WITH Base AS (SELECT DISTINCT `bi_vendas`.`vagas` AS `vagas` FROM `bi_vendas`) SELECT row_number() over ( order by if(`Base`.`vagas` is null,'Não Informado',`Base`.`vagas`)) AS `vagas_id`, if(`Base`.`vagas` is null,'Não Informado',`Base`.`vagas`) AS `vagas` FROM `Base`  ;

                DROP VIEW IF EXISTS `fAcessos`;
                DROP TABLE IF EXISTS `fAcessos`;
                CREATE TABLE IF NOT EXISTS  `fAcessos`  AS WITH Base AS (SELECT `a`.`id` AS `acesso_id`, date_format(`a`.`data`,'%d-%m-%Y') AS `data`, date_format(`a`.`data`,'%H') AS `hora`, `consultores`.`consultor_id` AS `consultor_id`, `unidades`.`unidade_id` AS `unidade_id` FROM ((`bi_acessos` `a` left join `dConsultores` `consultores` on(`consultores`.`consultor` = `a`.`nome`)) left join `dUnidades` `unidades` on(`unidades`.`unidade` = `a`.`unidade`))) SELECT `Base`.`acesso_id` AS `acesso_id`, `Base`.`data` AS `data`, `Base`.`hora` AS `hora`, `Base`.`consultor_id` AS `consultor_id`, `Base`.`unidade_id` AS `unidade_id` FROM `Base`  ;

                DROP VIEW IF EXISTS `fOportunidades`;
                DROP TABLE IF EXISTS `fOportunidades`;
                CREATE TABLE IF NOT EXISTS  `fOportunidades`  AS WITH Base AS (SELECT `o`.`oportunidade_id` AS `oportunidade_id`, `o`.`dias_finalizacao` AS `dias_finalizacao`, date_format(`o`.`data`,'%d-%m-%Y') AS `data`, date_format(`o`.`data`,'%H:%i:%s') AS `Hora`, `consultores`.`consultor_id` AS `consultor_id`, `unidades`.`unidade_id` AS `unidade_id`, `statuss`.`status_id` AS `status_id`, `etapas`.`funil_id` AS `funil_id`, `midias`.`midia_id` AS `midia_id`, `motivos`.`motivo_id` AS `motivo_id`, `categorias`.`categoria_id` AS `categoria_id`, `tipos`.`tipo_id` AS `tipo_id`, `regioes`.`regiao_id` AS `regiao_id`, `empreendimentos`.`empreendimento_id` AS `empreendimento_id`, `rendas`.`renda_id` AS `renda_id`, `estados_civis`.`estado_civil_id` AS `estado_civil_id`, `profissoes`.`profissao_id` AS `profissao_id`, `sexos`.`sexo_id` AS `sexo_id`, `interesses`.`interesse_id` AS `interesse_id`, `faixas_idades`.`idade_range_id` AS `idade_range_id`, `canais`.`canal_id` AS `canal_id`, `temperaturas`.`temperatura_id` AS `temperatura_id`, concat('https://argo.pixcrm.com.br/opportunities/manage?id=',`o`.`oportunidade_id`) AS `link_crm` FROM ((((((((((((((((((`vw_bi_oportunidades` `o` left join `dConsultores` `consultores` on(`consultores`.`consultor` = `o`.`consultor`)) left join `dUnidades` `unidades` on(`unidades`.`unidade` = `o`.`unidade`)) left join `dStatus` `statuss` on(`statuss`.`status` = `o`.`status`)) left join `dEtapasFunil` `etapas` on(`etapas`.`etapa_funil` = `o`.`etapa_funil`)) left join `dMidias` `midias` on(`midias`.`midia` = `o`.`midia`)) left join `dMotivosPerdaPausa` `motivos` on(`motivos`.`motivo_perda_pausa` = `o`.`motivo_perda_pausa`)) left join `dCategorias` `categorias` on(`categorias`.`categoria` = `o`.`categoria`)) left join `dTipos` `tipos` on(`tipos`.`tipo` = `o`.`tipo`)) left join `dRegioes` `regioes` on(`regioes`.`cidade` = `o`.`cidade` and `regioes`.`estado` = `o`.`estado`)) left join `dEmpreendimentos` `empreendimentos` on(`empreendimentos`.`empreendimento` = `o`.`empreendimento`)) left join `dRendas` `rendas` on(`rendas`.`renda` = `o`.`renda`)) left join `dEstadosCivis` `estados_civis` on(`estados_civis`.`estado_civil` = `o`.`estado_civil`)) left join `dProfissoes` `profissoes` on(`profissoes`.`profissao` = `o`.`profissao`)) left join `dSexos` `sexos` on(`sexos`.`sexo` = `o`.`sexo`)) left join `dInteresses` `interesses` on(`interesses`.`interesse` = `o`.`interesse`)) left join `dFaixasIdade` `faixas_idades` on(`faixas_idades`.`idade_range` = `o`.`idade_range`)) left join `dCanais` `canais` on(`canais`.`canal` = `o`.`canal`)) left join `dTemperaturas` `temperaturas` on(`temperaturas`.`temperatura` = `o`.`temperatura`))) SELECT `Base`.`oportunidade_id` AS `oportunidade_id`, `Base`.`dias_finalizacao` AS `dias_finalizacao`, `Base`.`data` AS `DATA`, `Base`.`Hora` AS `Hora`, `Base`.`consultor_id` AS `consultor_id`, `Base`.`unidade_id` AS `unidade_id`, `Base`.`status_id` AS `status_id`, `Base`.`funil_id` AS `funil_id`, `Base`.`midia_id` AS `midia_id`, `Base`.`motivo_id` AS `motivo_id`, `Base`.`categoria_id` AS `categoria_id`, `Base`.`tipo_id` AS `tipo_id`, `Base`.`regiao_id` AS `regiao_id`, `Base`.`empreendimento_id` AS `empreendimento_id`, `Base`.`renda_id` AS `renda_id`, `Base`.`estado_civil_id` AS `estado_civil_id`, `Base`.`profissao_id` AS `profissao_id`, `Base`.`sexo_id` AS `sexo_id`, `Base`.`interesse_id` AS `interesse_id`, `Base`.`idade_range_id` AS `idade_range_id`, `Base`.`canal_id` AS `canal_id`, `Base`.`temperatura_id` AS `temperatura_id`, `Base`.`link_crm` AS `link_crm` FROM `Base`  ;
                
                DROP VIEW IF EXISTS `dUTMs`;
                DROP TABLE IF EXISTS `dUTMs`;
                CREATE TABLE IF NOT EXISTS  `dUTMs`  AS SELECT row_number() over ( order by `bi_utms`.`oportunidade_id`) AS `utm_id`, `bi_utms`.`oportunidade_id` AS `oportunidade_id`, `bi_utms`.`tipo` AS `tipo`, `bi_utms`.`valor` AS `valor`, `o`.`consultor_id` AS `consultor_id`, `o`.`unidade_id` AS `unidade_id`, `o`.`funil_id` AS `funil_id`, `o`.`midia_id` AS `midia_id`, `o`.`motivo_id` AS `motivo_id`, `o`.`categoria_id` AS `categoria_id`, `o`.`tipo_id` AS `tipo_id`, `o`.`regiao_id` AS `regiao_id`, `o`.`renda_id` AS `renda_id`, `o`.`estado_civil_id` AS `estado_civil_id`, `o`.`profissao_id` AS `profissao_id`, `o`.`sexo_id` AS `sexo_id`, `o`.`interesse_id` AS `interesse_id`, `o`.`idade_range_id` AS `idade_range_id` FROM (`bi_utms` left join `fOportunidades` `o` on(`o`.`oportunidade_id` = `bi_utms`.`oportunidade_id`)) ;
                
                DROP VIEW IF EXISTS `fAcoesFunil`;
                DROP TABLE IF EXISTS `fAcoesFunil`;
                CREATE TABLE IF NOT EXISTS  `fAcoesFunil`  AS WITH Selected AS (SELECT `a`.`data` AS `data`, `etapas`.`funil_id` AS `funil_id`, `o`.`consultor_id` AS `consultor_id`, `o`.`unidade_id` AS `unidade_id`, `o`.`status_id` AS `status_id`, `o`.`midia_id` AS `midia_id`, `o`.`motivo_id` AS `motivo_id`, `o`.`categoria_id` AS `categoria_id`, `o`.`tipo_id` AS `tipo_id`, `o`.`regiao_id` AS `regiao_id`, `o`.`empreendimento_id` AS `empreendimento_id`, `o`.`renda_id` AS `renda_id`, `o`.`estado_civil_id` AS `estado_civil_id`, `o`.`profissao_id` AS `profissao_id`, `o`.`sexo_id` AS `sexo_id`, `o`.`interesse_id` AS `interesse_id`, `o`.`idade_range_id` AS `idade_range_id` FROM ((`bi_acoes_funil` `a` left join `dEtapasFunil` `etapas` on(`etapas`.`etapa_funil` = `a`.`etapa_funil`)) left join `fOportunidades` `o` on(`o`.`oportunidade_id` = `a`.`oportunidade_id`))) SELECT row_number() over ( order by `Selected`.`data`) AS `acao_id`, `Selected`.`data` AS `data`, `Selected`.`funil_id` AS `funil_id`, `Selected`.`consultor_id` AS `consultor_id`, `Selected`.`unidade_id` AS `unidade_id`, `Selected`.`status_id` AS `status_id`, `Selected`.`midia_id` AS `midia_id`, `Selected`.`motivo_id` AS `motivo_id`, `Selected`.`categoria_id` AS `categoria_id`, `Selected`.`tipo_id` AS `tipo_id`, `Selected`.`regiao_id` AS `regiao_id`, `Selected`.`empreendimento_id` AS `empreendimento_id`, `Selected`.`renda_id` AS `renda_id`, `Selected`.`estado_civil_id` AS `estado_civil_id`, `Selected`.`profissao_id` AS `profissao_id`, `Selected`.`sexo_id` AS `sexo_id`, `Selected`.`interesse_id` AS `interesse_id`, `Selected`.`idade_range_id` AS `idade_range_id` FROM `Selected`  ;

                DROP VIEW IF EXISTS `fAtividades`;
                DROP TABLE IF EXISTS `fAtividades`;
                CREATE TABLE IF NOT EXISTS  `fAtividades`  AS WITH Selected AS (SELECT `a`.`atividade_id` AS `atividade_id`, date_format(`a`.`data`,'%d-%m-%Y') AS `data`, `tipos_atividades`.`tipo_atividade_id` AS `tipo_atividade_id`, `status_atividades`.`status_atividade_id` AS `status_atividade_id`, `o`.`dias_finalizacao` AS `dias_finalizacao`, `o`.`consultor_id` AS `consultor_id`, `o`.`unidade_id` AS `unidade_id`, `o`.`status_id` AS `status_id`, `o`.`funil_id` AS `funil_id`, `o`.`midia_id` AS `midia_id`, `o`.`motivo_id` AS `motivo_id`, `o`.`categoria_id` AS `categoria_id`, `o`.`tipo_id` AS `tipo_id`, `o`.`regiao_id` AS `regiao_id`, `o`.`empreendimento_id` AS `empreendimento_id`, `o`.`renda_id` AS `renda_id`, `o`.`estado_civil_id` AS `estado_civil_id`, `o`.`profissao_id` AS `profissao_id`, `o`.`sexo_id` AS `sexo_id`, `o`.`interesse_id` AS `interesse_id`, `o`.`idade_range_id` AS `idade_range_id`, `o`.`canal_id` AS `canal_id`, `o`.`temperatura_id` AS `temperatura_id` FROM (((`bi_atividades` `a` left join `dTiposAtividade` `tipos_atividades` on(`tipos_atividades`.`tipo_atividade` = `a`.`tipo`)) left join `dStatusAtividade` `status_atividades` on(`status_atividades`.`status_atividade` = `a`.`status`)) left join `fOportunidades` `o` on(`o`.`oportunidade_id` = `a`.`oportunidade_id`))) SELECT `Selected`.`atividade_id` AS `atividade_id`, `Selected`.`data` AS `data`, `Selected`.`tipo_atividade_id` AS `tipo_atividade_id`, `Selected`.`status_atividade_id` AS `status_atividade_id`, `Selected`.`dias_finalizacao` AS `dias_finalizacao`, `Selected`.`consultor_id` AS `consultor_id`, `Selected`.`unidade_id` AS `unidade_id`, `Selected`.`status_id` AS `status_id`, `Selected`.`funil_id` AS `funil_id`, `Selected`.`midia_id` AS `midia_id`, `Selected`.`motivo_id` AS `motivo_id`, `Selected`.`categoria_id` AS `categoria_id`, `Selected`.`tipo_id` AS `tipo_id`, `Selected`.`regiao_id` AS `regiao_id`, `Selected`.`empreendimento_id` AS `empreendimento_id`, `Selected`.`renda_id` AS `renda_id`, `Selected`.`estado_civil_id` AS `estado_civil_id`, `Selected`.`profissao_id` AS `profissao_id`, `Selected`.`sexo_id` AS `sexo_id`, `Selected`.`interesse_id` AS `interesse_id`, `Selected`.`idade_range_id` AS `idade_range_id`, `Selected`.`canal_id` AS `canal_id`, `Selected`.`temperatura_id` AS `temperatura_id` FROM `Selected`  ;

                DROP VIEW IF EXISTS `fPropostas`;
                DROP TABLE IF EXISTS `fPropostas`;
                CREATE TABLE IF NOT EXISTS  `fPropostas`  AS WITH Selected AS (SELECT `p`.`proposta_id` AS `proposta_id`, date_format(`p`.`data_proposta`,'%d-%m-%Y') AS `data_proposta`, date_format(`p`.`data_venda`,'%d-%m-%Y') AS `data_venda`, `p`.`dias_fechamento` AS `dias_fechamento`, `p`.`valor` AS `valor`, `p`.`cancelada` AS `cancelada`, `o`.`consultor_id` AS `consultor_id`, `o`.`unidade_id` AS `unidade_id`, `o`.`funil_id` AS `funil_id`, `o`.`midia_id` AS `midia_id`, `o`.`motivo_id` AS `motivo_id`, `o`.`categoria_id` AS `categoria_id`, `o`.`tipo_id` AS `tipo_id`, `o`.`regiao_id` AS `regiao_id`, `o`.`renda_id` AS `renda_id`, `o`.`estado_civil_id` AS `estado_civil_id`, `o`.`profissao_id` AS `profissao_id`, `o`.`sexo_id` AS `sexo_id`, `o`.`interesse_id` AS `interesse_id`, `o`.`idade_range_id` AS `idade_range_id`, `fechamentos`.`fechamento_id` AS `fechamento_id`, `status_propostas`.`status_proposta_id` AS `status_proposta_id`, `unidades_empreendimentos`.`unidade_empreendimento_id` AS `unidade_empreendimento_id`, `o`.`empreendimento_id` AS `empreendimento_id`, concat('https://argo.pixcrm.com.br/proposals/manage?id=',`p`.`proposta_id`) AS `link_crm` FROM ((((`bi_propostas` `p` left join `fOportunidades` `o` on(`o`.`oportunidade_id` = `p`.`oportunidade_id`)) left join `dFechamentoDias` `fechamentos` on(`fechamentos`.`finalizacao_range` = `p`.`fechamento_range`)) left join `dStatusProposta` `status_propostas` on(`status_propostas`.`status_proposta` = `p`.`status_proposta`)) left join `dUnidadesEmpreendimento` `unidades_empreendimentos` on(`unidades_empreendimentos`.`empreendimento` = `p`.`empreendimento` and `unidades_empreendimentos`.`unidade` = `p`.`unidade`))) SELECT `Selected`.`proposta_id` AS `proposta_id`, `Selected`.`data_proposta` AS `data_proposta`, `Selected`.`data_venda` AS `data_venda`, `Selected`.`dias_fechamento` AS `dias_fechamento`, `Selected`.`valor` AS `valor`, `Selected`.`cancelada` AS `cancelada`, `Selected`.`consultor_id` AS `consultor_id`, `Selected`.`unidade_id` AS `unidade_id`, `Selected`.`funil_id` AS `funil_id`, `Selected`.`midia_id` AS `midia_id`, `Selected`.`motivo_id` AS `motivo_id`, `Selected`.`categoria_id` AS `categoria_id`, `Selected`.`tipo_id` AS `tipo_id`, `Selected`.`regiao_id` AS `regiao_id`, `Selected`.`renda_id` AS `renda_id`, `Selected`.`estado_civil_id` AS `estado_civil_id`, `Selected`.`profissao_id` AS `profissao_id`, `Selected`.`sexo_id` AS `sexo_id`, `Selected`.`interesse_id` AS `interesse_id`, `Selected`.`idade_range_id` AS `idade_range_id`, `Selected`.`fechamento_id` AS `fechamento_id`, `Selected`.`status_proposta_id` AS `status_proposta_id`, `Selected`.`unidade_empreendimento_id` AS `unidade_empreendimento_id`, `Selected`.`empreendimento_id` AS `empreendimento_id`, `Selected`.`link_crm` AS `link_crm` FROM `Selected`  ;

                DROP VIEW IF EXISTS `fVendas`;
                DROP TABLE IF EXISTS `fVendas`;
                CREATE TABLE IF NOT EXISTS  `fVendas`  AS WITH Selected AS (SELECT `v`.`venda_id` AS `venda_id`, date_format(`v`.`data_venda`,'%d-%m-%Y') AS `data_venda`, `v`.`dias_fechamento` AS `dias_fechamento`, `v`.`valor` AS `valor`, `o`.`consultor_id` AS `consultor_id`, `o`.`unidade_id` AS `unidade_id`, `o`.`funil_id` AS `funil_id`, `o`.`midia_id` AS `midia_id`, `o`.`motivo_id` AS `motivo_id`, `o`.`categoria_id` AS `categoria_id`, `o`.`tipo_id` AS `tipo_id`, `o`.`regiao_id` AS `regiao_id`, `o`.`renda_id` AS `renda_id`, `o`.`estado_civil_id` AS `estado_civil_id`, `o`.`profissao_id` AS `profissao_id`, `o`.`sexo_id` AS `sexo_id`, `o`.`interesse_id` AS `interesse_id`, `o`.`idade_range_id` AS `idade_range_id`, `fechamentos`.`fechamento_id` AS `fechamento_id`, `unidades_empreendimentos`.`unidade_empreendimento_id` AS `unidade_empreendimento_id`, `o`.`empreendimento_id` AS `empreendimento_id`, concat('https://argo.pixcrm.com.br/proposals/manage?id=',`v`.`venda_id`) AS `link_crm` FROM (((`bi_vendas` `v` left join `fOportunidades` `o` on(`o`.`oportunidade_id` = `v`.`oportunidade_id`)) left join `dFechamentoDias` `fechamentos` on(`fechamentos`.`finalizacao_range` = `v`.`fechamento_range`)) left join `dUnidadesEmpreendimento` `unidades_empreendimentos` on(`unidades_empreendimentos`.`empreendimento` = `v`.`empreendimento` and `unidades_empreendimentos`.`unidade` = `v`.`unidade`))) SELECT `Selected`.`venda_id` AS `venda_id`, `Selected`.`data_venda` AS `data_venda`, `Selected`.`dias_fechamento` AS `dias_fechamento`, `Selected`.`valor` AS `valor`, `Selected`.`consultor_id` AS `consultor_id`, `Selected`.`unidade_id` AS `unidade_id`, `Selected`.`funil_id` AS `funil_id`, `Selected`.`midia_id` AS `midia_id`, `Selected`.`motivo_id` AS `motivo_id`, `Selected`.`categoria_id` AS `categoria_id`, `Selected`.`tipo_id` AS `tipo_id`, `Selected`.`regiao_id` AS `regiao_id`, `Selected`.`renda_id` AS `renda_id`, `Selected`.`estado_civil_id` AS `estado_civil_id`, `Selected`.`profissao_id` AS `profissao_id`, `Selected`.`sexo_id` AS `sexo_id`, `Selected`.`interesse_id` AS `interesse_id`, `Selected`.`idade_range_id` AS `idade_range_id`, `Selected`.`fechamento_id` AS `fechamento_id`, `Selected`.`unidade_empreendimento_id` AS `unidade_empreendimento_id`, `Selected`.`empreendimento_id` AS `empreendimento_id`, `Selected`.`link_crm` AS `link_crm` FROM `Selected`  ;
                """
                
        try:
            # Split the SQL string into individual statements
            statements = sql.split(';')
            #self.stdout.write(self.style.NOTICE(f'{len(statements)} statements found'))
            # for statement in statements:
            #     # Skip empty statements (like trailing newlines)
            #     if statement.strip():
            #         with transaction.atomic():
            #             with connections['mysql'].cursor() as cursor:
            #                 cursor.execute(statement)
            self.stdout.write(self.style.NOTICE('Creating Star Schema with views...'))
            self.stdout.write(self.style.NOTICE('Calling CreateStarSchema() Procedure...'))
            with transaction.atomic():
                with connections['mysql'].cursor() as cursor:
                    cursor.execute("CALL CreateStarSchema();")
            self.stdout.write(self.style.SUCCESS('Star Schema created with views.'))
            logger.info('Star Schema created with views.')
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error creating views for Star Schema: {e}'))
            logger.error(f'Error creating views for Star Schema: {e}')
            raise e
        
        