-- V018_ROLLBACK.sql
-- Reversa de V018__create_product.sql — PRD-002.
--
-- Idempotente: cada paso usa IF EXISTS guards.
-- ADVERTENCIA: Ejecutar antes de V017_ROLLBACK (FK desde Product hacia ProductType).

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

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

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

-- 3. Drop HIDDEN columns + default constraints
IF COL_LENGTH('dbo.Product', 'ValidFrom') IS NOT NULL
BEGIN
    ALTER TABLE dbo.Product DROP CONSTRAINT IF EXISTS DF_Product_ValidFrom;
    ALTER TABLE dbo.Product DROP CONSTRAINT IF EXISTS DF_Product_ValidTo;
    ALTER TABLE dbo.Product DROP COLUMN ValidFrom, ValidTo;
    PRINT 'Product: ValidFrom/ValidTo columns dropped.';
END
GO

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

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

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

DELETE FROM dbo.Permiso WHERE Codigo = 'catalogo:productos:gestionar';
PRINT 'Permiso catalogo:productos:gestionar deleted.';
GO

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