BEGIN;

-- Drop new indexes
DROP INDEX IF EXISTS stock_logs_loggable_type_loggable_id_idx;
DROP INDEX IF EXISTS stock_logs_product_warehouse_id_idx;
DROP INDEX IF EXISTS stock_logs_created_by_idx;
DROP INDEX IF EXISTS stock_logs_created_at_idx;

-- Restore obsolete columns
ALTER TABLE stock_logs
    ADD COLUMN IF NOT EXISTS transaction_type VARCHAR(20) DEFAULT '' NOT NULL,
    ADD COLUMN IF NOT EXISTS quantity NUMERIC(15, 3) DEFAULT 0 NOT NULL,
    ADD COLUMN IF NOT EXISTS before_quantity NUMERIC(15, 3) DEFAULT 0 NOT NULL,
    ADD COLUMN IF NOT EXISTS after_quantity NUMERIC(15, 3) DEFAULT 0 NOT NULL,
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(),
    ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;

-- Rename columns back
ALTER TABLE stock_logs
    RENAME COLUMN loggable_type TO log_type;

ALTER TABLE stock_logs
    RENAME COLUMN loggable_id TO log_id;

ALTER TABLE stock_logs
    RENAME COLUMN notes TO note;

-- Drop new columns
ALTER TABLE stock_logs
    DROP COLUMN IF EXISTS increase,
    DROP COLUMN IF EXISTS decrease;

-- Restore indexes for old structure
CREATE INDEX IF NOT EXISTS stock_logs_product_warehouse_id_idx ON stock_logs (product_warehouse_id);

CREATE INDEX IF NOT EXISTS stock_logs_log_type_log_id_idx ON stock_logs (log_type, log_id);

CREATE INDEX IF NOT EXISTS stock_logs_created_by_idx ON stock_logs (created_by);

CREATE INDEX IF NOT EXISTS stock_logs_created_at_idx ON stock_logs (created_at);

CREATE INDEX IF NOT EXISTS stock_logs_deleted_at_idx ON stock_logs (deleted_at);

COMMIT;
