-- V019_ROLLBACK.sql
-- PRD-003: Reversa de V019__create_product_prices.sql.
--
-- Pasos:
--   1. Deshabilita SYSTEM_VERSIONING en dbo.ProductPrices (requerido antes de DROP TABLE).
--   2. Elimina el PERIOD FOR SYSTEM_TIME y las columnas hidden SysStartTime/SysEndTime.
--   3. Drop de dbo.ProductPrices_History.
--   4. Drop de dbo.ProductPrices (y sus constraints + índices en cascada).
--   5. Drop de dbo.usp_AddProductPrice.
--
-- ADVERTENCIA: destruye todo el historial de precios. Ejecutar sólo en DEV o TEST.
-- Run on: SIGCM2 (dev), SIGCM2_Test_App, SIGCM2_Test_Api.

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

-- 1. Deshabilita SYSTEM_VERSIONING (imprescindible antes de DROP TABLE temporal).
IF EXISTS (SELECT 1 FROM sys.tables WHERE object_id = OBJECT_ID('dbo.ProductPrices') AND temporal_type = 2)
BEGIN
    ALTER TABLE dbo.ProductPrices SET (SYSTEM_VERSIONING = OFF);
    PRINT 'ProductPrices: SYSTEM_VERSIONING = OFF.';
END
GO

-- 2. Elimina el PERIOD y las hidden cols (si existen, independientemente del versioning).
IF COL_LENGTH('dbo.ProductPrices', 'SysStartTime') IS NOT NULL
BEGIN
    ALTER TABLE dbo.ProductPrices
    DROP PERIOD FOR SYSTEM_TIME;

    -- Drop default constraints antes de drop de columnas.
    IF EXISTS (SELECT 1 FROM sys.default_constraints WHERE name = 'DF_ProductPrices_SysStartTime')
        ALTER TABLE dbo.ProductPrices DROP CONSTRAINT DF_ProductPrices_SysStartTime;
    IF EXISTS (SELECT 1 FROM sys.default_constraints WHERE name = 'DF_ProductPrices_SysEndTime')
        ALTER TABLE dbo.ProductPrices DROP CONSTRAINT DF_ProductPrices_SysEndTime;

    ALTER TABLE dbo.ProductPrices DROP COLUMN SysStartTime;
    ALTER TABLE dbo.ProductPrices DROP COLUMN SysEndTime;
    PRINT 'ProductPrices: PERIOD + hidden cols dropped.';
END
GO

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

-- 4. Drop de la tabla principal (constraints + índices en cascada).
IF OBJECT_ID(N'dbo.ProductPrices', N'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.ProductPrices;
    PRINT 'Table dbo.ProductPrices dropped.';
END
GO

-- 5. Drop del SP.
IF OBJECT_ID(N'dbo.usp_AddProductPrice', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE dbo.usp_AddProductPrice;
    PRINT 'Procedure dbo.usp_AddProductPrice dropped.';
END
GO

PRINT '';
PRINT 'V019 rollback complete — dbo.ProductPrices, dbo.ProductPrices_History, dbo.usp_AddProductPrice removed.';
GO
