-- V014_ROLLBACK.sql
-- Reversa de V014__create_tablas_fiscales.sql.
--
-- ADVERTENCIA: ejecutar ELIMINA TipoDeIva, IngresosBrutos, sus historiales temporales,
--   el permiso 'administracion:fiscal:gestionar' y sus asignaciones.
--
-- Uso intended: ROLLBACK en entornos NO-productivos.
-- Prerequisito: no deben existir FKs vivas apuntando a estas tablas (FAC-001, etc.).
--   Si FAC-001 ya esta aplicado, este rollback fallara — usar backup.
--
-- Idempotente: seguro para re-ejecutar (guards en cada paso).

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

-- ═══════════════════════════════════════════════════════════════════════
-- 1. Apagar SYSTEM_VERSIONING — TipoDeIva
-- ═══════════════════════════════════════════════════════════════════════

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

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

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

-- ═══════════════════════════════════════════════════════════════════════
-- 2. Apagar SYSTEM_VERSIONING — IngresosBrutos
-- ═══════════════════════════════════════════════════════════════════════

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

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

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

-- ═══════════════════════════════════════════════════════════════════════
-- 3. Drop FK self antes de DROP TABLE (para evitar constraint violation)
-- ═══════════════════════════════════════════════════════════════════════

IF OBJECT_ID('FK_TipoDeIva_Predecesor', 'F') IS NOT NULL
BEGIN
    ALTER TABLE dbo.TipoDeIva DROP CONSTRAINT FK_TipoDeIva_Predecesor;
    PRINT 'FK_TipoDeIva_Predecesor dropped.';
END
GO

IF OBJECT_ID('FK_IIBB_Predecesor', 'F') IS NOT NULL
BEGIN
    ALTER TABLE dbo.IngresosBrutos DROP CONSTRAINT FK_IIBB_Predecesor;
    PRINT 'FK_IIBB_Predecesor dropped.';
END
GO

-- ═══════════════════════════════════════════════════════════════════════
-- 4. Drop history tables → main tables
-- ═══════════════════════════════════════════════════════════════════════

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

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

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

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

-- ═══════════════════════════════════════════════════════════════════════
-- 5. Remover permiso 'administracion:fiscal:gestionar' + RolPermiso
-- ═══════════════════════════════════════════════════════════════════════

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

DELETE FROM dbo.Permiso
WHERE Codigo = 'administracion:fiscal:gestionar';
GO

PRINT '';
PRINT 'V014 rolled back.';
PRINT '  - dbo.TipoDeIva and dbo.TipoDeIva_History removed.';
PRINT '  - dbo.IngresosBrutos and dbo.IngresosBrutos_History removed.';
PRINT '  - Permiso administracion:fiscal:gestionar removed.';
GO
