-- 재고 보정 테이블 추가
-- 재고 조정/보정 내역을 기록

CREATE TABLE IF NOT EXISTS stock_adjustments (
    adjustment_id     INTEGER PRIMARY KEY AUTOINCREMENT,
    adjustment_date   DATE NOT NULL,
    adjustment_no     TEXT,                  -- 보정 번호 (ADJ-YYYYMMDD-XXXX)
    adjustment_type   TEXT NOT NULL CHECK(adjustment_type IN ('LOSS', 'FOUND', 'RECOUNT', 'DAMAGE', 'EXPIRE')),
    -- LOSS: 감모(손실), FOUND: 발견, RECOUNT: 재고조사, DAMAGE: 파손, EXPIRE: 유통기한
    notes             TEXT,
    created_by        TEXT,                  -- 보정 담당자 (나중에 계정 연동)
    created_at        DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- 재고 보정 상세 (로트별)
CREATE TABLE IF NOT EXISTS stock_adjustment_details (
    detail_id         INTEGER PRIMARY KEY AUTOINCREMENT,
    adjustment_id     INTEGER NOT NULL,
    herb_item_id      INTEGER NOT NULL,
    lot_id            INTEGER NOT NULL,
    quantity_before   REAL NOT NULL,         -- 보정 전 재고
    quantity_after    REAL NOT NULL,         -- 보정 후 재고
    quantity_delta    REAL NOT NULL,         -- 증감량
    reason            TEXT,                  -- 보정 사유
    created_at        DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (adjustment_id) REFERENCES stock_adjustments(adjustment_id),
    FOREIGN KEY (herb_item_id) REFERENCES herb_items(herb_item_id),
    FOREIGN KEY (lot_id) REFERENCES inventory_lots(lot_id)
);

-- 인덱스 생성
CREATE INDEX IF NOT EXISTS idx_stock_adjustments_date ON stock_adjustments(adjustment_date);
CREATE INDEX IF NOT EXISTS idx_adjustment_details_herb ON stock_adjustment_details(herb_item_id);
CREATE INDEX IF NOT EXISTS idx_adjustment_details_lot ON stock_adjustment_details(lot_id);
