-- ════════════════════════════════════════════════════════════
-- 마이그레이션: 콤보(세트) 출고 원장 set_movement 추가
--   기존 운영 malaysia_stock_db 에 적용(신규 설치는 init 에 이미 포함).
--   superuser/owner 로 실행. 멱등(IF NOT EXISTS).
-- ════════════════════════════════════════════════════════════
CREATE TABLE IF NOT EXISTS set_movement (
    id             BIGSERIAL   PRIMARY KEY,
    movement_date  DATE        NOT NULL,
    warehouse_code TEXT        NOT NULL REFERENCES warehouses(warehouse_code),
    set_code       TEXT        NOT NULL CHECK (set_code LIKE 'MY-%'),
    movement_type  TEXT        NOT NULL DEFAULT 'OUT' CHECK (movement_type IN ('OUT', 'ADJUST')),
    qty            INTEGER     NOT NULL,
    ref_type       TEXT        NOT NULL DEFAULT '',
    ref_no         TEXT        NOT NULL DEFAULT '',
    memo           TEXT        NOT NULL DEFAULT '',
    created_by     TEXT        NOT NULL DEFAULT '',
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK ((movement_type = 'OUT' AND qty > 0) OR movement_type = 'ADJUST')
);
CREATE INDEX IF NOT EXISTS idx_set_mv_wh_set ON set_movement (warehouse_code, set_code);
CREATE INDEX IF NOT EXISTS idx_set_mv_date   ON set_movement (movement_date);

GRANT SELECT, INSERT, UPDATE, DELETE ON set_movement TO malaysia_app;
GRANT USAGE, SELECT ON SEQUENCE set_movement_id_seq TO malaysia_app;

SELECT 'set_movement ready' AS status;
