-- Migration: 005_scope_tenant_table_versions
-- MySQL 5.6 compatible. Safe both after the legacy 001 and the scoped 001.
SET @scope_column_count = (
  SELECT COUNT(*)
  FROM information_schema.columns
  WHERE table_schema = DATABASE()
    AND table_name = 'nfse_tenant_table_versions'
    AND column_name IN ('ambiente', 'perfil')
);

DELETE FROM nfse_tenant_table_versions
WHERE @scope_column_count = 0;

SET @migration_005_sql = IF(
  @scope_column_count = 0,
  'ALTER TABLE nfse_tenant_table_versions
     DROP KEY uk_nfse_tenant_table_versions_siafi_version,
     ADD COLUMN ambiente ENUM(''producao_restrita'', ''producao'') NOT NULL AFTER codigo_siafi,
     ADD COLUMN perfil ENUM(''municipio'', ''contribuinte'') NOT NULL AFTER ambiente,
     ADD UNIQUE KEY uk_nfse_tenant_table_versions_scope_version
       (codigo_siafi, ambiente, perfil, table_version)',
  'SELECT 1'
);

PREPARE migration_005_statement FROM @migration_005_sql;
EXECUTE migration_005_statement;
DEALLOCATE PREPARE migration_005_statement;
