USE bulo;

SET @col_veiculo_ativo := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'usuarios' AND COLUMN_NAME = 'id_veiculo_ativo'
);
SET @sql := IF(@col_veiculo_ativo = 0, 'ALTER TABLE usuarios ADD COLUMN id_veiculo_ativo INT NULL AFTER disponivel', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @idx_veiculo_ativo := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'usuarios' AND INDEX_NAME = 'idx_usuarios_veiculo_ativo'
);
SET @sql := IF(@idx_veiculo_ativo = 0, 'ALTER TABLE usuarios ADD INDEX idx_usuarios_veiculo_ativo (id_veiculo_ativo)', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @fk_veiculo_ativo := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'usuarios' AND CONSTRAINT_NAME = 'fk_usuarios_veiculo_ativo'
);
SET @sql := IF(
  @fk_veiculo_ativo = 0,
  'ALTER TABLE usuarios ADD CONSTRAINT fk_usuarios_veiculo_ativo FOREIGN KEY (id_veiculo_ativo) REFERENCES veiculos(id) ON DELETE SET NULL',
  'SELECT 1'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
