BEGIN;

-- ─── PART_BOM_REPORT staging + INSERT ──
CREATE TEMP TABLE pbr_stage (
  objid varchar,
  customer_objid varchar,
  contract_objid varchar,
  unit_code varchar,
  status varchar,
  writer varchar,
  regdate timestamp,
  multi_yn varchar,
  multi_master_yn varchar,
  multi_break_yn varchar,
  multi_master_objid varchar,
  product_cd varchar,
  part_no varchar,
  part_name varchar,
  revision varchar,
  note varchar,
  editer varchar,
  edit_date timestamp,
  deploy_date varchar
);
\copy pbr_stage FROM '/tmp/pbr_long.csv' WITH CSV HEADER

INSERT INTO part_bom_report (
  objid, customer_objid, contract_objid, unit_code, status, writer, regdate,
  multi_yn, multi_master_yn, multi_break_yn, multi_master_objid,
  product_cd, part_no, part_name, revision, note, editer, edit_date, deploy_date
)
SELECT
  objid, customer_objid, contract_objid, unit_code, status, writer, regdate,
  multi_yn, multi_master_yn, multi_break_yn, multi_master_objid,
  product_cd, part_no, part_name, revision, note, editer, edit_date, deploy_date
FROM pbr_stage
ON CONFLICT (objid) DO NOTHING;

-- ─── BOM_PART_QTY staging + INSERT ──
CREATE TEMP TABLE bpq_stage (
  bom_report_objid varchar,
  objid varchar,
  parent_objid varchar,
  child_objid varchar,
  parent_part_no varchar,
  part_no varchar,
  qty numeric,
  item_qty numeric,
  qty_temp numeric,
  regdate timestamp,
  writer varchar,
  seq bigint,
  status varchar,
  last_part_objid varchar,
  deploy_user_id varchar,
  deploy_date varchar
);
\copy bpq_stage FROM '/tmp/bpq_long.csv' WITH CSV HEADER

INSERT INTO bom_part_qty (
  bom_report_objid, objid, parent_objid, child_objid, parent_part_no, part_no,
  qty, item_qty, qty_temp, regdate, writer, seq, status, last_part_objid,
  deploy_user_id, deploy_date
)
SELECT
  bom_report_objid, objid, parent_objid, child_objid, parent_part_no, part_no,
  qty, item_qty, qty_temp, regdate, writer, seq, status, last_part_objid,
  deploy_user_id, deploy_date
FROM bpq_stage
ON CONFLICT (objid) DO NOTHING;

COMMIT;

SELECT 'PART_BOM_REPORT:' AS label, COUNT(*) FROM part_bom_report WHERE objid = '1038014721'
UNION ALL
SELECT 'BOM_PART_QTY:', COUNT(*) FROM bom_part_qty WHERE bom_report_objid = '1038014721';
