CREATE TABLE IF NOT EXISTS wh_special_adjustment (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  adjustment_no VARCHAR(50) NOT NULL,
  warehouse_id BIGINT NOT NULL,
  warehouse_type VARCHAR(32) NOT NULL,
  direction VARCHAR(32) NOT NULL,
  reason VARCHAR(1000) NOT NULL,
  status VARCHAR(32) NOT NULL,
  operator_user_id BIGINT NULL,
  adjusted_at DATETIME NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_wh_special_adjustment_no (adjustment_no),
  KEY idx_wh_special_adjustment_warehouse (warehouse_id, adjusted_at),
  KEY idx_wh_special_adjustment_direction (direction, adjusted_at),
  CONSTRAINT fk_special_adjustment_warehouse FOREIGN KEY (warehouse_id) REFERENCES wh_warehouse(id),
  CONSTRAINT fk_special_adjustment_operator FOREIGN KEY (operator_user_id) REFERENCES sys_user(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS wh_special_adjustment_line (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  adjustment_id BIGINT NOT NULL,
  line_no INT NOT NULL,
  item_id BIGINT NOT NULL,
  warehouse_id BIGINT NOT NULL,
  location_id BIGINT NULL,
  lot_id BIGINT NOT NULL,
  inventory_txn_id BIGINT NULL,
  before_qty DECIMAL(18,6) NOT NULL DEFAULT 0,
  change_qty DECIMAL(18,6) NOT NULL DEFAULT 0,
  after_qty DECIMAL(18,6) NOT NULL DEFAULT 0,
  before_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0,
  change_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0,
  after_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0,
  unit_cost DECIMAL(18,4) NOT NULL DEFAULT 0,
  line_reason VARCHAR(1000) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_wh_special_adjustment_line_adjustment (adjustment_id),
  KEY idx_wh_special_adjustment_line_item (item_id),
  KEY idx_wh_special_adjustment_line_lot (lot_id),
  KEY idx_wh_special_adjustment_line_txn (inventory_txn_id),
  CONSTRAINT fk_special_adjustment_line_adjustment FOREIGN KEY (adjustment_id) REFERENCES wh_special_adjustment(id),
  CONSTRAINT fk_special_adjustment_line_item FOREIGN KEY (item_id) REFERENCES md_item(id),
  CONSTRAINT fk_special_adjustment_line_warehouse FOREIGN KEY (warehouse_id) REFERENCES wh_warehouse(id),
  CONSTRAINT fk_special_adjustment_line_location FOREIGN KEY (location_id) REFERENCES wh_location(id),
  CONSTRAINT fk_special_adjustment_line_lot FOREIGN KEY (lot_id) REFERENCES wh_stock_lot(id),
  CONSTRAINT fk_special_adjustment_line_inventory_txn FOREIGN KEY (inventory_txn_id) REFERENCES wh_inventory_txn(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
