-- Agrega el giro de negocio a la empresa para activar modulos verticales

SET @col_exists := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'empresas'
      AND column_name = 'giro_negocio_id'
);
SET @sql := IF(
    @col_exists = 0,
    'ALTER TABLE empresas ADD COLUMN giro_negocio_id BIGINT UNSIGNED NULL AFTER tipo_empresa_id',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @idx_exists := (
    SELECT COUNT(*)
    FROM information_schema.statistics
    WHERE table_schema = DATABASE()
      AND table_name = 'empresas'
      AND index_name = 'idx_empresas_giro_negocio'
);
SET @sql := IF(
    @idx_exists = 0,
    'ALTER TABLE empresas ADD KEY idx_empresas_giro_negocio (giro_negocio_id)',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @fk_exists := (
    SELECT COUNT(*)
    FROM information_schema.table_constraints
    WHERE table_schema = DATABASE()
      AND table_name = 'empresas'
      AND constraint_name = 'fk_empresas_giro_negocio'
);
SET @sql := IF(
    @fk_exists = 0,
    'ALTER TABLE empresas ADD CONSTRAINT fk_empresas_giro_negocio FOREIGN KEY (giro_negocio_id) REFERENCES giro_negocio(id)',
    'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
