BEGIN;

-- Drop old indexes tied to removed columns
DROP INDEX IF EXISTS stock_logs_log_type_log_id_idx;
DROP INDEX IF EXISTS stock_logs_deleted_at_idx;

-- Rename columns to new naming
ALTER TABLE stock_logs
    RENAME COLUMN log_type TO loggable_type;

ALTER TABLE stock_logs
    RENAME COLUMN log_id TO loggable_id;

ALTER TABLE stock_logs
    RENAME COLUMN note TO notes;

-- Add new increase/decrease columns
ALTER TABLE stock_logs
    ADD COLUMN IF NOT EXISTS increase NUMERIC(15, 3) DEFAULT 0,
    ADD COLUMN IF NOT EXISTS decrease NUMERIC(15, 3) DEFAULT 0;

-- Adjust column definitions
ALTER TABLE stock_logs
    ALTER COLUMN loggable_type TYPE VARCHAR(50),
    ALTER COLUMN loggable_type SET NOT NULL,
    ALTER COLUMN loggable_id SET NOT NULL,
    ALTER COLUMN increase SET DEFAULT 0,
    ALTER COLUMN increase SET NOT NULL,
    ALTER COLUMN decrease SET DEFAULT 0,
    ALTER COLUMN decrease SET NOT NULL;

-- Remove obsolete columns
ALTER TABLE stock_logs
    DROP COLUMN IF EXISTS transaction_type,
    DROP COLUMN IF EXISTS quantity,
    DROP COLUMN IF EXISTS before_quantity,
    DROP COLUMN IF EXISTS after_quantity,
    DROP COLUMN IF EXISTS updated_at,
    DROP COLUMN IF EXISTS deleted_at;

-- Recreate indexes for new 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_loggable_type_loggable_id_idx ON stock_logs (loggable_type, loggable_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);

COMMIT;
