-- ===============================================================
--  ROLLBACK: Remove FIFO fields from STOCK_TRANSFER_DETAILS
-- ===============================================================

-- Drop indexes
DROP INDEX IF EXISTS idx_stock_transfer_details_dest_pw;
DROP INDEX IF EXISTS idx_stock_transfer_details_source_pw;

-- Drop foreign keys
DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'fk_stock_transfer_details_source_pw'
    ) THEN
        EXECUTE 'ALTER TABLE stock_transfer_details
                 DROP CONSTRAINT fk_stock_transfer_details_source_pw';
    END IF;

    IF EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'fk_stock_transfer_details_dest_pw'
    ) THEN
        EXECUTE 'ALTER TABLE stock_transfer_details
                 DROP CONSTRAINT fk_stock_transfer_details_dest_pw';
    END IF;
END $$;

-- Drop FIFO columns
ALTER TABLE stock_transfer_details
DROP COLUMN IF EXISTS total_used,
DROP COLUMN IF EXISTS total_qty,
DROP COLUMN IF EXISTS pending_qty,
DROP COLUMN IF EXISTS usage_qty,
DROP COLUMN IF EXISTS dest_product_warehouse_id,
DROP COLUMN IF EXISTS source_product_warehouse_id;

-- Restore original columns (in case rollback)
ALTER TABLE stock_transfer_details
ADD COLUMN IF NOT EXISTS quantity NUMERIC(15, 3) NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS before_quantity NUMERIC(15, 3),
ADD COLUMN IF NOT EXISTS after_quantity NUMERIC(15, 3);
