-- realistic_mock_data.sql
-- 幂等脚本：在 dev 环境创建更真实的测试数据
-- 使用说明：在 Supabase SQL Editor 中选择 Role = postgres，整体执行此文件。

-- 运行前确保至少存在一个 auth 用户，否则后续插入会违背 FK
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM auth.users) THEN
    RAISE EXCEPTION 'No auth.users found. Create at least one auth user in Supabase auth or sign up once, then re-run this script.';
  END IF;
END$$;
-- 1) 确保存在一个测试分类
INSERT INTO public.ml_categories (id, cid, name, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_categories_cid_seq'::regclass), '测试分类-配送端', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_categories WHERE name = '测试分类-配送端');

-- 2) 创建或复用商家（优先按 email 匹配，否则按任意 auth.user）
INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(),
  COALESCE((SELECT id FROM auth.users WHERE email='merchant.real@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)),
  'merchant.real@example.com','real_merchant', NOW()
WHERE NOT EXISTS (
  SELECT 1 FROM public.ak_users WHERE email='merchant.real@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='merchant.real@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1))
);

-- 3) 三个真实感顾客（按 email 或存在的 auth.users id 复用）
INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(), COALESCE((SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)), 'zhang.san@example.com','张三', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email='zhang.san@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)));

INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(), COALESCE((SELECT id FROM auth.users WHERE email='li.si@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)), 'li.si@example.com','李四', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email='li.si@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='li.si@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)));

INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(), COALESCE((SELECT id FROM auth.users WHERE email='wang.wu@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)), 'wang.wu@example.com','王五', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email='wang.wu@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='wang.wu@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)));

-- 4) 五个商品（使用上面分类与商家）
INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-A-20260202','鲜榨橙汁 500ml',12.50,200,'https://cdn.example.com/orange.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-A-20260202');

INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-B-20260202','经典牛肉饼 200g',35.00,120,'https://cdn.example.com/beef.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-B-20260202');

INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-C-20260202','手工三明治',22.00,80,'https://cdn.example.com/sandwich.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-C-20260202');

INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-D-20260202','每日现磨咖啡',18.00,150,'https://cdn.example.com/coffee.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-D-20260202');

-- 5) 创建若干订单与配送任务（status = 1, driver_id = NULL）
-- 订单 1（示例已更新：order_no / phone / address）
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'TEST-DELIV-20260202-001',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  12.50,3.00,15.50,
  ('{"contact":"张三","phone":"13890001111","province":"北京市","city":"北京市","district":"朝阳区","street":"望京街道","detail":"望京SOHO 1号楼"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-001');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-001' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-A-20260202' LIMIT 1), '鲜榨橙汁 500ml',12.50,1,12.50,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-001');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-001' LIMIT 1),
  ('{"contact":"门店A","phone":"13990001111","detail":"门店A 地址"}')::jsonb,
  ('{"contact":"张三","phone":"13890001111","detail":"望京SOHO 1号楼"}')::jsonb,
  3.00,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-001');

-- 订单 2（示例已更新）
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'TEST-DELIV-20260202-002',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='li.si@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='li.si@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  35.00,4.00,39.00,
  ('{"contact":"李四","phone":"13890002222","province":"上海市","city":"上海市","district":"静安区","street":"南京西路","detail":"静安寺附近"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-002');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-002' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-B-20260202' LIMIT 1), '经典牛肉饼 200g',35.00,1,35.00,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-002');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-002' LIMIT 1),
  ('{"contact":"门店B","phone":"13990002222","detail":"门店B 地址"}')::jsonb,
  ('{"contact":"李四","phone":"13890002222","detail":"静安寺附近"}')::jsonb,
  4.00,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-002');

-- 订单 3（示例已更新）
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'TEST-DELIV-20260202-003',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='wang.wu@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='wang.wu@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  22.00,3.50,25.50,
  ('{"contact":"王五","phone":"13890003333","province":"广东省","city":"广州市","district":"天河区","street":"体育西路","detail":"天河城附近"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-003');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-003' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-C-20260202' LIMIT 1), '手工三明治',22.00,1,22.00,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-003');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-003' LIMIT 1),
  ('{"contact":"门店C","phone":"13990003333","detail":"门店C 地址"}')::jsonb,
  ('{"contact":"王五","phone":"13890003333","detail":"天河城附近"}')::jsonb,
  3.50,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-003');

-- 订单 4（示例已更新）
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'TEST-DELIV-20260202-004',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  18.00,3.00,21.00,
  ('{"contact":"张三","phone":"13890001111","province":"上海市","city":"上海市","district":"浦东新区","street":"世纪大道","detail":"世纪汇 10 号"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-004');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-004' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-D-20260202' LIMIT 1), '每日现磨咖啡',18.00,1,18.00,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-004');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-004' LIMIT 1),
  ('{"contact":"门店D","phone":"13990004444","detail":"门店D 地址"}')::jsonb,
  ('{"contact":"张三","phone":"13890001111","detail":"世纪汇 10 号"}')::jsonb,
  3.00,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='TEST-DELIV-20260202-004');

-- 最终返回已创建或已存在的关键 id，便于验证
SELECT
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1) AS merchant_id,
  (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1) AS custA_id,
  (SELECT id FROM public.ak_users WHERE email='li.si@example.com' LIMIT 1) AS custB_id,
  (SELECT id FROM public.ak_users WHERE email='wang.wu@example.com' LIMIT 1) AS custC_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-A-20260202' LIMIT 1) AS productA_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-B-20260202' LIMIT 1) AS productB_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-C-20260202' LIMIT 1) AS productC_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-D-20260202' LIMIT 1) AS productD_id,
  (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-001' LIMIT 1) AS order1_id,
  (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-002' LIMIT 1) AS order2_id,
  (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-003' LIMIT 1) AS order3_id,
  (SELECT id FROM public.ml_orders WHERE order_no='TEST-DELIV-20260202-004' LIMIT 1) AS order4_id;

-- 6) 批量生成 20 个“待接取”订单（幂等）
-- 订单号格式：PENDING-20260202-001 .. PENDING-20260202-020
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT t.order_no, t.user_id, t.merchant_id, t.product_amount, t.shipping_fee, t.total_amount, t.shipping_address, NOW(), NOW()
FROM (
  SELECT format('PENDING-20260202-%s', lpad(i::text,3,'0')) AS order_no,
    COALESCE(
      CASE (i % 3)
        WHEN 1 THEN (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1)
        WHEN 2 THEN (SELECT id FROM public.ak_users WHERE email='li.si@example.com' LIMIT 1)
        ELSE (SELECT id FROM public.ak_users WHERE email='wang.wu@example.com' LIMIT 1)
      END,
      (SELECT id FROM public.ak_users LIMIT 1)
    ) AS user_id,
    (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1) AS merchant_id,
    (SELECT base_price FROM public.ml_products WHERE product_code='REAL-P-A-20260202' LIMIT 1) AS product_amount,
    3.00 AS shipping_fee,
    (SELECT base_price FROM public.ml_products WHERE product_code='REAL-P-A-20260202' LIMIT 1) + 3.00 AS total_amount,
    jsonb_build_object('contact', CASE WHEN (i % 3)=1 THEN '张三' WHEN (i % 3)=2 THEN '李四' ELSE '王五' END, 'phone', '138900' || lpad(i::text,5,'0'), 'detail', '自动生成地址 ' || i) AS shipping_address
  FROM generate_series(1,20) AS s(i)
) AS t
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders o WHERE o.order_no = t.order_no);

-- 生成对应的 order_items（若不存在）
INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), o.id, p.id, p.name, p.base_price, 1, p.base_price, NOW()
FROM public.ml_orders o
JOIN public.ml_products p ON p.product_code = 'REAL-P-A-20260202'
WHERE o.order_no LIKE 'PENDING-20260202-%'
  AND NOT EXISTS (SELECT 1 FROM public.ml_order_items oi WHERE oi.order_id = o.id);

-- 生成对应的 delivery_tasks（status = 1）
WITH no AS (
  SELECT id, order_no, shipping_address, ROW_NUMBER() OVER (ORDER BY id) AS rn
  FROM public.ml_orders WHERE order_no LIKE 'PENDING-20260202-%'
)
INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT no.id,
  jsonb_build_object('contact','自动门店','phone', '13900' || lpad(no.rn::text,4,'0'),'detail','自动门店地址')::jsonb,
  no.shipping_address,
  3.00,1,NOW(),NOW()
FROM no
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt WHERE dt.order_id = no.id);
-- realistic_mock_data.sql
-- 幂等脚本：在 dev 环境创建更真实的测试数据
-- 使用说明：在 Supabase SQL Editor 中选择 Role = postgres，整体执行此文件。

-- 运行前确保至少存在一个 auth 用户，否则后续插入会违背 FK
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM auth.users) THEN
    RAISE EXCEPTION 'No auth.users found. Create at least one auth user in Supabase auth or sign up once, then re-run this script.';
  END IF;
END$$;
-- 1) 确保存在一个测试分类
INSERT INTO public.ml_categories (id, cid, name, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_categories_cid_seq'::regclass), '测试分类-配送端', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_categories WHERE name = '测试分类-配送端');

-- 2) 创建或复用商家（优先按 email 匹配，否则按任意 auth.user）
INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(),
  COALESCE((SELECT id FROM auth.users WHERE email='merchant.real@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)),
  'merchant.real@example.com','real_merchant', NOW()
WHERE NOT EXISTS (
  SELECT 1 FROM public.ak_users WHERE email='merchant.real@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='merchant.real@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1))
);

-- 3) 三个真实感顾客（按 email 或存在的 auth.users id 复用）
INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(), COALESCE((SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)), 'zhang.san@example.com','张三', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email='zhang.san@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)));

INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(), COALESCE((SELECT id FROM auth.users WHERE email='li.si@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)), 'li.si@example.com','李四', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email='li.si@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='li.si@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)));

INSERT INTO public.ak_users (id, auth_id, email, username, created_at)
SELECT uuid_generate_v4(), COALESCE((SELECT id FROM auth.users WHERE email='wang.wu@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)), 'wang.wu@example.com','王五', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email='wang.wu@example.com' OR auth_id = COALESCE((SELECT id FROM auth.users WHERE email='wang.wu@example.com' LIMIT 1),(SELECT id FROM auth.users LIMIT 1)));

-- 4) 五个商品（使用上面分类与商家）
INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-A-20260202','鲜榨橙汁 500ml',12.50,200,'https://cdn.example.com/orange.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-A-20260202');

INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-B-20260202','经典牛肉饼 200g',35.00,120,'https://cdn.example.com/beef.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-B-20260202');

INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-C-20260202','手工三明治',22.00,80,'https://cdn.example.com/sandwich.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-C-20260202');

INSERT INTO public.ml_products (id, cid, merchant_id, category_id, product_code, name, base_price, total_stock, main_image_url, created_at)
SELECT uuid_generate_v4(), nextval('public.ml_products_cid_seq'::regclass),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  (SELECT id FROM public.ml_categories WHERE name='测试分类-配送端' LIMIT 1),
  'REAL-P-D-20260202','每日现磨咖啡',18.00,150,'https://cdn.example.com/coffee.jpg', NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_products WHERE product_code='REAL-P-D-20260202');

-- 5) 创建若干订单与配送任务（status = 1, driver_id = NULL）
-- 订单 1
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'REAL-ORD-20260202-001',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  12.50,3.00,15.50,
  ('{"contact":"张三","phone":"13811112222","province":"北京市","city":"北京市","district":"朝阳区","street":"望京街道","detail":"望京SOHO 1号楼"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-001');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-001' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-A-20260202' LIMIT 1), '鲜榨橙汁 500ml',12.50,1,12.50,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-001');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-001' LIMIT 1),
  ('{"contact":"门店A","phone":"13920001111","detail":"门店A 地址"}')::jsonb,
  ('{"contact":"张三","phone":"13811112222","detail":"望京SOHO 1号楼"}')::jsonb,
  3.00,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-001');

-- 订单 2
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'REAL-ORD-20260202-002',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='li.si@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='li.si@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  35.00,4.00,39.00,
  ('{"contact":"李四","phone":"13822223333","province":"上海市","city":"上海市","district":"静安区","street":"南京西路","detail":"静安寺附近"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-002');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-002' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-B-20260202' LIMIT 1), '经典牛肉饼 200g',35.00,1,35.00,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-002');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-002' LIMIT 1),
  ('{"contact":"门店B","phone":"13920002222","detail":"门店B 地址"}')::jsonb,
  ('{"contact":"李四","phone":"13822223333","detail":"静安寺附近"}')::jsonb,
  4.00,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-002');

-- 订单 3
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'REAL-ORD-20260202-003',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='wang.wu@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='wang.wu@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  22.00,3.50,25.50,
  ('{"contact":"王五","phone":"13833334444","province":"广东省","city":"广州市","district":"天河区","street":"体育西路","detail":"天河城附近"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-003');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-003' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-C-20260202' LIMIT 1), '手工三明治',22.00,1,22.00,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-003');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-003' LIMIT 1),
  ('{"contact":"门店C","phone":"13920003333","detail":"门店C 地址"}')::jsonb,
  ('{"contact":"王五","phone":"13833334444","detail":"天河城附近"}')::jsonb,
  3.50,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-003');

-- 订单 4
INSERT INTO public.ml_orders (order_no, user_id, merchant_id, product_amount, shipping_fee, total_amount, shipping_address, created_at, updated_at)
SELECT 'REAL-ORD-20260202-004',
  COALESCE(
    (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1),
    (SELECT id FROM public.ak_users WHERE auth_id=(SELECT id FROM auth.users WHERE email='zhang.san@example.com' LIMIT 1) LIMIT 1),
    (SELECT id FROM public.ak_users LIMIT 1)
  ),
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1),
  18.00,3.00,21.00,
  ('{"contact":"张三","phone":"13811112222","province":"上海市","city":"上海市","district":"浦东新区","street":"世纪大道","detail":"世纪汇 10 号"}')::jsonb,
  NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-004');

INSERT INTO public.ml_order_items (id, order_id, product_id, product_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-004' LIMIT 1), (SELECT id FROM public.ml_products WHERE product_code='REAL-P-D-20260202' LIMIT 1), '每日现磨咖啡',18.00,1,18.00,NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_order_items oi JOIN public.ml_orders o ON oi.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-004');

INSERT INTO public.ml_delivery_tasks (order_id, pickup_address, delivery_address, delivery_fee, status, created_at, updated_at)
SELECT (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-004' LIMIT 1),
  ('{"contact":"门店D","phone":"13920004444","detail":"门店D 地址"}')::jsonb,
  ('{"contact":"张三","phone":"13811112222","detail":"世纪汇 10 号"}')::jsonb,
  3.00,1,NOW(),NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks dt JOIN public.ml_orders o ON dt.order_id=o.id WHERE o.order_no='REAL-ORD-20260202-004');

-- 最终返回已创建或已存在的关键 id，便于验证
SELECT
  (SELECT id FROM public.ak_users WHERE email='merchant.real@example.com' LIMIT 1) AS merchant_id,
  (SELECT id FROM public.ak_users WHERE email='zhang.san@example.com' LIMIT 1) AS custA_id,
  (SELECT id FROM public.ak_users WHERE email='li.si@example.com' LIMIT 1) AS custB_id,
  (SELECT id FROM public.ak_users WHERE email='wang.wu@example.com' LIMIT 1) AS custC_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-A-20260202' LIMIT 1) AS productA_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-B-20260202' LIMIT 1) AS productB_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-C-20260202' LIMIT 1) AS productC_id,
  (SELECT id FROM public.ml_products WHERE product_code='REAL-P-D-20260202' LIMIT 1) AS productD_id,
  (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-001' LIMIT 1) AS order1_id,
  (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-002' LIMIT 1) AS order2_id,
  (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-003' LIMIT 1) AS order3_id,
  (SELECT id FROM public.ml_orders WHERE order_no='REAL-ORD-20260202-004' LIMIT 1) AS order4_id;
