-- V016_ROLLBACK.sql
-- Reversa de V016__create_rubro.sql.
--
-- ⚠️  ADVERTENCIA: ejecutar ELIMINA dbo.Rubro, dbo.Rubro_History,
--     el permiso 'catalogo:rubros:gestionar' y sus asignaciones.
--
-- Uso intended: ROLLBACK en entornos NO-productivos.
-- Prerequisito: no deben existir FKs vivas apuntando a Rubro (p.ej., Producto, Tarifario).
--               Si CAT-002..006 o PRC-001 ya están aplicados, agregar TarifarioBaseId FK,
--               este rollback fallará — usar backup.

SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
GO

-- ═══════════════════════════════════════════════════════════════════════
-- 1. Apagar SYSTEM_VERSIONING + remover PERIOD en Rubro
-- ═══════════════════════════════════════════════════════════════════════

IF EXISTS (SELECT 1 FROM sys.tables WHERE object_id = OBJECT_ID('dbo.Rubro') AND temporal_type = 2)
BEGIN
    ALTER TABLE dbo.Rubro SET (SYSTEM_VERSIONING = OFF);
    PRINT 'Rubro: SYSTEM_VERSIONING OFF.';
END
GO

IF EXISTS (SELECT 1 FROM sys.periods WHERE object_id = OBJECT_ID('dbo.Rubro'))
BEGIN
    ALTER TABLE dbo.Rubro DROP PERIOD FOR SYSTEM_TIME;
    PRINT 'Rubro: PERIOD FOR SYSTEM_TIME dropped.';
END
GO

IF COL_LENGTH('dbo.Rubro', 'ValidFrom') IS NOT NULL
BEGIN
    ALTER TABLE dbo.Rubro DROP CONSTRAINT IF EXISTS DF_Rubro_ValidFrom;
    ALTER TABLE dbo.Rubro DROP CONSTRAINT IF EXISTS DF_Rubro_ValidTo;
    ALTER TABLE dbo.Rubro DROP COLUMN ValidFrom, ValidTo;
    PRINT 'Rubro: ValidFrom/ValidTo dropped.';
END
GO

IF OBJECT_ID(N'dbo.Rubro_History', N'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.Rubro_History;
    PRINT 'Rubro_History dropped.';
END
GO

-- ═══════════════════════════════════════════════════════════════════════
-- 2. Drop índices + tabla Rubro
-- ═══════════════════════════════════════════════════════════════════════

-- Self-FK must be dropped before dropping the table (SQL Server handles it
-- automatically when the table is dropped, but explicit is safer).

IF OBJECT_ID(N'dbo.Rubro', N'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.Rubro;
    PRINT 'Table dbo.Rubro dropped.';
END
GO

-- ═══════════════════════════════════════════════════════════════════════
-- 3. Remover permiso 'catalogo:rubros:gestionar' + RolPermiso
-- ═══════════════════════════════════════════════════════════════════════

DELETE rp
FROM dbo.RolPermiso rp
JOIN dbo.Permiso p ON p.Id = rp.PermisoId
WHERE p.Codigo = 'catalogo:rubros:gestionar';
GO

DELETE FROM dbo.Permiso
WHERE Codigo = 'catalogo:rubros:gestionar';
GO

PRINT '';
PRINT 'V016 rolled back. dbo.Rubro and dbo.Rubro_History removed.';
PRINT 'catalogo:rubros:gestionar permission and role assignment removed.';
GO
