-- V017_ROLLBACK.sql
-- Reversa de V017__create_product_type.sql.
-- PRD-001: ProductType rollback.
--
-- ADVERTENCIA: Si PRD-002 ya fue mergeado (IProductQueryRepository real), hacer rollback
-- de PRD-002 primero (la interfaz es removida por esta rollback).
--
-- Idempotente: cada paso usa IF EXISTS guards.

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

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

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

-- 3. Remover columnas HIDDEN + default constraints
IF COL_LENGTH('dbo.ProductType', 'ValidFrom') IS NOT NULL
BEGIN
    ALTER TABLE dbo.ProductType DROP CONSTRAINT IF EXISTS DF_ProductType_ValidFrom;
    ALTER TABLE dbo.ProductType DROP CONSTRAINT IF EXISTS DF_ProductType_ValidTo;
    ALTER TABLE dbo.ProductType DROP COLUMN ValidFrom, ValidTo;
    PRINT 'ProductType: ValidFrom/ValidTo columns dropped.';
END
GO

-- 4. Drop history table
IF OBJECT_ID(N'dbo.ProductType_History', N'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.ProductType_History;
    PRINT 'Table dbo.ProductType_History dropped.';
END
GO

-- 5. Drop main table
IF OBJECT_ID(N'dbo.ProductType', N'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.ProductType;
    PRINT 'Table dbo.ProductType dropped.';
END
GO

-- 6. Remover RolPermiso para catalogo:tipos:gestionar
DELETE rp FROM dbo.RolPermiso rp
    JOIN dbo.Permiso p ON p.Id = rp.PermisoId
    WHERE p.Codigo = 'catalogo:tipos:gestionar';
PRINT 'RolPermiso rows for catalogo:tipos:gestionar deleted.';
GO

-- 7. Remover Permiso
DELETE FROM dbo.Permiso WHERE Codigo = 'catalogo:tipos:gestionar';
PRINT 'Permiso catalogo:tipos:gestionar deleted.';
GO

PRINT '';
PRINT 'V017 rolled back successfully.';
GO
