-- Migration: Create adjustment_stocks table for FIFO tracking
-- This table tracks FIFO allocation for stock adjustments (both increase and decrease)

BEGIN;

CREATE TABLE IF NOT EXISTS adjustment_stocks (
    id BIGSERIAL PRIMARY KEY,
    stock_log_id BIGINT NOT NULL,
    product_warehouse_id BIGINT NOT NULL,

    -- FIFO fields for Adjustment INCREASE (Stockable)
    -- Tracks stock added to warehouse via adjustment
    total_qty NUMERIC(15, 3) DEFAULT 0,
    total_used NUMERIC(15, 3) DEFAULT 0,

    -- FIFO fields for Adjustment DECREASE (Usable)
    -- Tracks stock consumed from warehouse via adjustment
    usage_qty NUMERIC(15, 3) DEFAULT 0,
    pending_qty NUMERIC(15, 3) DEFAULT 0,

    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- Foreign keys
ALTER TABLE adjustment_stocks
ADD CONSTRAINT fk_adjustment_stocks_stock_log
FOREIGN KEY (stock_log_id) REFERENCES stock_logs(id)
ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE adjustment_stocks
ADD CONSTRAINT fk_adjustment_stocks_product_warehouse
FOREIGN KEY (product_warehouse_id) REFERENCES product_warehouses(id)
ON DELETE CASCADE ON UPDATE CASCADE;

-- Indexes
CREATE INDEX idx_adjustment_stocks_stock_log ON adjustment_stocks(stock_log_id);
CREATE INDEX idx_adjustment_stocks_product_warehouse ON adjustment_stocks(product_warehouse_id);

COMMIT;
