DROP TEMPORARY TABLE IF EXISTS tmp_raw_lot_rename;
DROP TEMPORARY TABLE IF EXISTS tmp_raw_lot_existing_seq;

CREATE TEMPORARY TABLE tmp_raw_lot_existing_seq AS
SELECT
  l.item_id,
  COALESCE(
    MAX(
      CASE
        WHEN REPLACE(l.lot_no, CONCAT('JH_', i.item_code, '_'), '') REGEXP '^[0-9]{4}$'
        THEN CAST(REPLACE(l.lot_no, CONCAT('JH_', i.item_code, '_'), '') AS UNSIGNED)
        ELSE 0
      END
    ),
    0
  ) AS max_seq
FROM wh_stock_lot l
JOIN md_item i ON i.id = l.item_id
JOIN wh_warehouse w ON w.id = l.warehouse_id
WHERE i.item_type = 'RAW_MATERIAL'
  AND w.warehouse_type = 'RAW'
  AND l.lot_no LIKE CONCAT('JH_', i.item_code, '_%')
GROUP BY l.item_id;

CREATE TEMPORARY TABLE tmp_raw_lot_rename AS
SELECT
  ranked.lot_id,
  ranked.old_lot_no,
  CONCAT('JH_', ranked.item_code, '_', LPAD(ranked.max_seq + ranked.seq_no, 4, '0')) AS new_lot_no
FROM (
  SELECT
    l.id AS lot_id,
    l.item_id,
    i.item_code,
    l.lot_no AS old_lot_no,
    COALESCE(seq.max_seq, 0) AS max_seq,
    ROW_NUMBER() OVER (PARTITION BY l.item_id ORDER BY l.id) AS seq_no
  FROM wh_stock_lot l
  JOIN md_item i ON i.id = l.item_id
  JOIN wh_warehouse w ON w.id = l.warehouse_id
  LEFT JOIN tmp_raw_lot_existing_seq seq ON seq.item_id = l.item_id
  WHERE i.item_type = 'RAW_MATERIAL'
    AND w.warehouse_type = 'RAW'
    AND l.lot_no NOT LIKE CONCAT('JH_', i.item_code, '_%')
) ranked;

UPDATE po_receipt_item pri
JOIN tmp_raw_lot_rename map ON map.old_lot_no = pri.lot_no
SET pri.lot_no = map.new_lot_no;

UPDATE pp_work_order_material_issue issue_row
JOIN tmp_raw_lot_rename map ON map.old_lot_no = issue_row.material_sub_batch_no
SET issue_row.material_sub_batch_no = map.new_lot_no;

UPDATE pp_completion_receipt_item item_row
JOIN tmp_raw_lot_rename map ON map.old_lot_no = item_row.source_material_sub_batch_no
SET item_row.source_material_sub_batch_no = map.new_lot_no;

UPDATE wh_stock_lot source_row
JOIN tmp_raw_lot_rename map ON map.old_lot_no = source_row.material_sub_batch_no
SET source_row.material_sub_batch_no = map.new_lot_no;

UPDATE wh_stock_lot source_row
JOIN tmp_raw_lot_rename map ON map.old_lot_no = source_row.source_material_sub_batch_no
SET source_row.source_material_sub_batch_no = map.new_lot_no;

UPDATE wh_stocktake_line line_row
JOIN tmp_raw_lot_rename map ON map.old_lot_no = line_row.lot_no
SET line_row.lot_no = map.new_lot_no;

UPDATE wh_stocktake_line line_row
JOIN tmp_raw_lot_rename map ON map.old_lot_no = line_row.source_material_sub_batch_no
SET line_row.source_material_sub_batch_no = map.new_lot_no;

UPDATE wh_stock_lot lot_row
JOIN tmp_raw_lot_rename map ON map.lot_id = lot_row.id
SET lot_row.lot_no = map.new_lot_no;

DROP TEMPORARY TABLE IF EXISTS tmp_raw_lot_rename;
DROP TEMPORARY TABLE IF EXISTS tmp_raw_lot_existing_seq;
