-- =====================================================================================
-- 测试环境种子数据（仅写入 platform_express_* 三表）
--
-- 目的：在测试/预发环境使用“生产同款表结构”联调页面与接口，避免创建 mock_* 表。
-- 适用：已执行 express_tracking_platform_upgrade.sql 后。
--
-- 注意：
-- - 本文件会插入示例数据：大多数 tracking_no 以 TEST_ 前缀开头；另有 1 条 ORDER_PLACED 示例运单号为空。
-- - 如需清理，可执行文末的清理 SQL。
-- =====================================================================================

BEGIN;

-- 兼容旧版本种子数据：曾使用 TEST_YT_20260206_0010 作为“已下单”示例
-- 现要求：已下单运单号为空；因此先清理旧 tracking_no 相关记录，避免重复数据。
-- DELETE FROM public.platform_express_tracking_events WHERE tracking_no = 'TEST_YT_20260206_0010';
-- DELETE FROM public.platform_express_event_raw WHERE tracking_no = 'TEST_YT_20260206_0010';
-- DELETE FROM public.platform_express_waybills WHERE carrier = 'YTO' AND tracking_no = 'TEST_YT_20260206_0010' AND order_no = 'ORD_TEST_20260206010';

-- 1) 创建/更新示例运单（若已存在则跳过）
INSERT INTO public.platform_express_waybills (
  order_id,
  order_no,
  carrier,
  tracking_no,
  source,
  current_status_code,
  current_status_text,
  eta,
  last_synced_at
)
VALUES
  (NULL, 'ORD_TEST_20260206001', 'YUNDA', 'TEST_YD_20260206_0001', 'mock', 'IN_TRANSIT', '运输中', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206002', 'YTO',   'TEST_YT_20260206_0002', 'mock', 'OUT_FOR_DELIVERY', '派送中', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206003', 'ZTO',   'TEST_ZT_20260206_0003', 'mock', 'DELIVERED', '已签收', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206004', 'STO',   'TEST_STO_20260206_0004', 'mock', 'EXCEPTION', '异常', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206005', 'SF',    'TEST_SF_20260206_0005', 'mock', 'IN_TRANSIT', '运输中', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206006', 'YUNDA', 'TEST_YD_20260206_0006', 'mock', 'SHIPPED', '已发货', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206007', 'YTO',   'TEST_YT_20260206_0007', 'mock', 'IN_TRANSIT', '运输中', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206008', 'ZTO',   'TEST_ZT_20260206_0008', 'mock', 'OUT_FOR_DELIVERY', '派送中', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206010', 'YTO',   '', 'mock', 'ORDER_PLACED', '已下单', NULL, NOW()),
  (NULL, 'ORD_TEST_20260206011', 'ZTO',   'TEST_ZT_20260206_0011', 'mock', 'READY_FOR_PICKUP', '待取件', NULL, NOW())
ON CONFLICT (carrier, tracking_no) DO NOTHING;


-- 2) 插入轨迹事件（幂等：按 (waybill_id, dedupe_key) 去重）
WITH w AS (
  SELECT id, carrier, tracking_no
  FROM public.platform_express_waybills
  WHERE tracking_no IN (
    'TEST_YD_20260206_0001',
    'TEST_YT_20260206_0002',
    'TEST_ZT_20260206_0003',
    'TEST_STO_20260206_0004',
    'TEST_SF_20260206_0005',
    'TEST_YD_20260206_0006',
    'TEST_YT_20260206_0007',
    'TEST_ZT_20260206_0008',
    '',
    'TEST_ZT_20260206_0011'
  )
)
INSERT INTO public.platform_express_tracking_events (
  waybill_id,
  carrier,
  tracking_no,
  event_id,
  event_time,
  event_code,
  event_text,
  status_code,
  node_name,
  location,
  description,
  evidence_urls,
  raw_payload,
  received_at,
  source,
  dedupe_key
)
SELECT * FROM (
  -- 运单 1：运输中
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YD_20260206_0001') AS waybill_id,
    'YUNDA' AS carrier,
    'TEST_YD_20260206_0001' AS tracking_no,
    'test_e_1001' AS event_id,
    NOW() - INTERVAL '12 hours' AS event_time,
    'PICKED' AS event_code,
    '包裹已揽收' AS event_text,
    'IN_TRANSIT' AS status_code,
    '上海浦东集散中心' AS node_name,
    '上海市 浦东新区' AS location,
    NULL AS description,
    '[]'::jsonb AS evidence_urls,
    NULL::jsonb AS raw_payload,
    NOW() AS received_at,
    'poll' AS source,
    'test_e_1001' AS dedupe_key
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YD_20260206_0001'),
    'YUNDA',
    'TEST_YD_20260206_0001',
    'test_e_1002',
    NOW() - INTERVAL '6 hours',
    'TRANSIT',
    '运输中（测试数据）',
    'IN_TRANSIT',
    '上海浦东集散中心',
    '上海市 浦东新区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_1002'

  -- 运单 2：派送中
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YT_20260206_0002'),
    'YTO',
    'TEST_YT_20260206_0002',
    'test_e_2001',
    NOW() - INTERVAL '8 hours',
    'ARRIVAL',
    '运输中',
    'IN_TRANSIT',
    '广州天河网点',
    '广州市 天河区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_2001'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YT_20260206_0002'),
    'YTO',
    'TEST_YT_20260206_0002',
    'test_e_2002',
    NOW() - INTERVAL '1 hours',
    'OUT_FOR_DELIVERY',
    '派送员正在派件（测试数据）',
    'OUT_FOR_DELIVERY',
    '广州天河网点',
    '广州市 天河区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_2002'

  -- 运单 3：已签收
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_ZT_20260206_0003'),
    'ZTO',
    'TEST_ZT_20260206_0003',
    'test_e_3001',
    NOW() - INTERVAL '2 days',
    'PICKED',
    '包裹已揽收',
    'IN_TRANSIT',
    '北京朝阳网点',
    '北京市 朝阳区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_3001'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_ZT_20260206_0003'),
    'ZTO',
    'TEST_ZT_20260206_0003',
    'test_e_3002',
    NOW() - INTERVAL '1 days',
    'TRANSIT',
    '快件运输中',
    'IN_TRANSIT',
    '北京朝阳网点',
    '北京市 朝阳区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_3002'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_ZT_20260206_0003'),
    'ZTO',
    'TEST_ZT_20260206_0003',
    'test_e_3003',
    NOW() - INTERVAL '12 hours',
    'DELIVERED',
    '您的快件已签收（测试数据）',
    'DELIVERED',
    '北京朝阳网点',
    '北京市 朝阳区',
    NULL,
    '["https://img-shop.gmugmu.com/mock/pod_sample.png"]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_3003'

  -- 运单 4：异常
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_STO_20260206_0004'),
    'STO',
    'TEST_STO_20260206_0004',
    'test_e_4001',
    NOW() - INTERVAL '20 hours',
    'PICKED',
    '包裹已揽收',
    'IN_TRANSIT',
    '深圳南山网点',
    '深圳市 南山区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_4001'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_STO_20260206_0004'),
    'STO',
    'TEST_STO_20260206_0004',
    'test_e_4002',
    NOW() - INTERVAL '2 hours',
    'EXCEPTION',
    '【包裹异常】收件地址不详，等待处理（测试数据）',
    'EXCEPTION',
    '深圳南山网点',
    '深圳市 南山区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_4002'

  -- 运单 5：运输中（不区分中转/到达节点/分拨）
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_SF_20260206_0005'),
    'SF',
    'TEST_SF_20260206_0005',
    'test_e_5001',
    NOW() - INTERVAL '10 hours',
    'PICKED',
    '包裹已揽收',
    'IN_TRANSIT',
    '南京江宁集散中心',
    '南京市 江宁区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_5001'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_SF_20260206_0005'),
    'SF',
    'TEST_SF_20260206_0005',
    'test_e_5002',
    NOW() - INTERVAL '30 minutes',
    'ARRIVAL',
    '运输中（测试数据）',
    'IN_TRANSIT',
    '南京江宁网点',
    '南京市 江宁区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_5002'

  -- 运单 6：已发货（待揽收）
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YD_20260206_0006'),
    'YUNDA',
    'TEST_YD_20260206_0006',
    'test_e_6001',
    NOW() - INTERVAL '5 hours',
    'SHIPPED',
    '商家已发货，等待快递公司揽收（测试数据）',
    'SHIPPED',
    NULL,
    '杭州市 余杭区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'manual',
    'test_e_6001'

  -- 运单 7：运输中
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YT_20260206_0007'),
    'YTO',
    'TEST_YT_20260206_0007',
    'test_e_7001',
    NOW() - INTERVAL '18 hours',
    'PICKED',
    '包裹已揽收',
    'IN_TRANSIT',
    '武汉江夏网点',
    '武汉市 江夏区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_7001'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_YT_20260206_0007'),
    'YTO',
    'TEST_YT_20260206_0007',
    'test_e_7002',
    NOW() - INTERVAL '7 hours',
    'TRANSIT',
    '运输中（测试数据）',
    'IN_TRANSIT',
    '武汉江夏网点',
    '武汉市 江夏区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_7002'

  -- 运单 8：派送中
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_ZT_20260206_0008'),
    'ZTO',
    'TEST_ZT_20260206_0008',
    'test_e_8001',
    NOW() - INTERVAL '9 hours',
    'ARRIVAL',
    '运输中（测试数据）',
    'IN_TRANSIT',
    '西安高新网点',
    '西安市 雁塔区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'poll',
    'test_e_8001'
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_ZT_20260206_0008'),
    'ZTO',
    'TEST_ZT_20260206_0008',
    'test_e_8002',
    NOW() - INTERVAL '20 minutes',
    'OUT_FOR_DELIVERY',
    '派送员正在派件（测试数据）',
    'OUT_FOR_DELIVERY',
    '西安高新网点',
    '西安市 雁塔区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_8002'

  -- 运单 9：已下单（平台生成事件示例；运单号为空）
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = ''),
    'YTO',
    '',
    'test_e_10001',
    NOW() - INTERVAL '1 days',
    'ORDER_PLACED',
    '订单已下单（测试数据）',
    'ORDER_PLACED',
    NULL,
    NULL,
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'manual',
    'test_e_10001'

  -- 运单 10：待取件（到驿站/自提柜）
  UNION ALL
  SELECT
    (SELECT id FROM w WHERE tracking_no = 'TEST_ZT_20260206_0011'),
    'ZTO',
    'TEST_ZT_20260206_0011',
    'test_e_11001',
    NOW() - INTERVAL '3 hours',
    'READY_FOR_PICKUP',
    '快件已到达【杭州余杭菜鸟驿站】，请凭取件码取件（测试数据）',
    'READY_FOR_PICKUP',
    '杭州余杭菜鸟驿站',
    '杭州市 余杭区',
    NULL,
    '[]'::jsonb,
    NULL::jsonb,
    NOW(),
    'webhook',
    'test_e_11001'
) AS rows_to_insert
WHERE rows_to_insert.waybill_id IS NOT NULL
ON CONFLICT (waybill_id, dedupe_key) DO NOTHING;


-- 3) 可选：插入原始接收留痕（用于演示验签/排障界面）
INSERT INTO public.platform_express_event_raw (
  received_at,
  source,
  client_id,
  carrier,
  tracking_no,
  signature_valid,
  signature,
  ts_header,
  request_id,
  remote_ip,
  headers,
  body,
  parse_error,
  dedupe_key
)
VALUES (
  NOW(),
  'webhook',
  'test_client',
  'YTO',
  'TEST_YT_20260206_0002',
  TRUE,
  'test-signature',
  EXTRACT(EPOCH FROM NOW())::text,
  'req_test_0001',
  '127.0.0.1',
  '{"content-type":"application/json"}'::jsonb,
  '{"tracking_no":"TEST_YT_20260206_0002","status_code":"OUT_FOR_DELIVERY","event_text":"派送员正在派件（测试数据）"}'::jsonb,
  NULL,
  'raw_test_0001'
);

INSERT INTO public.platform_express_event_raw (
  received_at,
  source,
  client_id,
  carrier,
  tracking_no,
  signature_valid,
  signature,
  ts_header,
  request_id,
  remote_ip,
  headers,
  body,
  parse_error,
  dedupe_key
)
VALUES (
  NOW(),
  'poll',
  'test_client',
  'STO',
  'TEST_STO_20260206_0004',
  NULL,
  NULL,
  EXTRACT(EPOCH FROM NOW())::text,
  'req_test_0002',
  '127.0.0.1',
  '{"content-type":"application/json"}'::jsonb,
  '{"tracking_no":"TEST_STO_20260206_0004","status_code":"EXCEPTION","event_text":"【包裹异常】收件地址不详，等待处理（测试数据）"}'::jsonb,
  NULL,
  'raw_test_0002'
);

-- ORDER_PLACED 示例：允许 tracking_no 为空，但 raw body 中保留 order_no 便于排障/审计筛选
INSERT INTO public.platform_express_event_raw (
  received_at,
  source,
  client_id,
  carrier,
  tracking_no,
  signature_valid,
  signature,
  ts_header,
  request_id,
  remote_ip,
  headers,
  body,
  parse_error,
  dedupe_key
)
VALUES (
  NOW(),
  'webhook',
  'test_client',
  'YTO',
  NULL,
  TRUE,
  'test-signature',
  EXTRACT(EPOCH FROM NOW())::text,
  'req_test_0003',
  '127.0.0.1',
  '{"content-type":"application/json"}'::jsonb,
  '{"order_no":"ORD_TEST_20260206010","tracking_no":"","status_code":"ORDER_PLACED","event_text":"已下单（测试数据）"}'::jsonb,
  NULL,
  'raw_test_0003'
);

COMMIT;

-- =====================================================================================
-- 清理（需要时手工执行）
-- =====================================================================================
-- BEGIN;
-- DELETE FROM public.platform_express_event_raw WHERE tracking_no LIKE 'TEST_%' OR (body->>'order_no') = 'ORD_TEST_20260206010';
-- DELETE FROM public.platform_express_tracking_events WHERE tracking_no LIKE 'TEST_%' OR status_code = 'ORDER_PLACED';
-- DELETE FROM public.platform_express_waybills WHERE tracking_no LIKE 'TEST_%' OR order_no = 'ORD_TEST_20260206010';
-- COMMIT;
