-- create_test_orders.sql
-- 幂等的测试订单生成脚本：
-- 1) 确保必需的 ak_users, ml_categories, ml_products, ml_product_skus 存在
-- 2) 插入 3 个订单（含 order_items）并为每个订单创建 ml_delivery_tasks
-- 3) 适用于 complete_mall_database.sql 所建表（在 Supabase SQL Editor 中以 postgres 角色运行）

BEGIN;

-- 1. 确保测试用户存在（若不存在则插入简化记录）
-- 使用 WHERE NOT EXISTS 保证幂等
INSERT INTO public.ak_users(id, auth_id, username, role, email, phone, avatar_url, status, registration_source, created_at, updated_at)
SELECT uuid_generate_v4(), uuid_generate_v4(), '系统管理员', 'admin', 'admin@mall.com', '13800138000', NULL, 'active', 'script', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email = 'admin@mall.com');

INSERT INTO public.ak_users(id, auth_id, username, role, email, phone, avatar_url, status, registration_source, created_at, updated_at)
SELECT uuid_generate_v4(), uuid_generate_v4(), '数码专营店', 'merchant', 'merchant1@mall.com', '13800138001', NULL, 'active', 'script', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email = 'merchant1@mall.com');

INSERT INTO public.ak_users(id, auth_id, username, role, email, phone, avatar_url, status, registration_source, created_at, updated_at)
SELECT uuid_generate_v4(), uuid_generate_v4(), '时尚小铺', 'merchant', 'merchant2@mall.com', '13800138002', NULL, 'active', 'script', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email = 'merchant2@mall.com');

INSERT INTO public.ak_users(id, auth_id, username, role, email, phone, avatar_url, status, registration_source, created_at, updated_at)
SELECT uuid_generate_v4(), uuid_generate_v4(), '张小明', 'customer', 'customer1@mall.com', '13800138101', NULL, 'active', 'script', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email = 'customer1@mall.com');

INSERT INTO public.ak_users(id, auth_id, username, role, email, phone, avatar_url, status, registration_source, created_at, updated_at)
SELECT uuid_generate_v4(), uuid_generate_v4(), '李小红', 'customer', 'customer2@mall.com', '13800138102', NULL, 'active', 'script', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email = 'customer2@mall.com');

INSERT INTO public.ak_users(id, auth_id, username, role, email, phone, avatar_url, status, registration_source, created_at, updated_at)
SELECT uuid_generate_v4(), uuid_generate_v4(), '快递小哥1', 'delivery', 'driver1@mall.com', '13800138201', NULL, 'active', 'script', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ak_users WHERE email = 'driver1@mall.com');

-- 2. 确保至少有一个分类存在
INSERT INTO public.ml_categories (id, name, slug, level, path, created_at, updated_at)
SELECT uuid_generate_v4(), '默认分类', 'default', 1, ARRAY['默认分类'], NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM public.ml_categories);

-- 3. 为每个商家确保至少有一个商品和 SKU
-- 3.1 Helper: 若商家没有商品则插入一个最小商品
WITH merchant1 AS (
    SELECT id AS merchant_id FROM public.ak_users WHERE email = 'merchant1@mall.com' LIMIT 1
), merchant2 AS (
    SELECT id AS merchant_id FROM public.ak_users WHERE email = 'merchant2@mall.com' LIMIT 1
), default_cat AS (
    SELECT id AS category_id FROM public.ml_categories LIMIT 1
)
-- 插入商品（商家1）
INSERT INTO public.ml_products (id, merchant_id, category_id, product_code, name, base_price, total_stock, available_stock, created_at, updated_at)
SELECT uuid_generate_v4(), m.merchant_id, d.category_id, 'P-M1-001', '示例商品 - 商家1', 199.00, 50, 50, NOW(), NOW()
FROM merchant1 m, default_cat d
WHERE NOT EXISTS (
    SELECT 1 FROM public.ml_products p WHERE p.merchant_id = m.merchant_id LIMIT 1
);

-- 插入商品（商家2）
INSERT INTO public.ml_products (id, merchant_id, category_id, product_code, name, base_price, total_stock, available_stock, created_at, updated_at)
SELECT uuid_generate_v4(),
       (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com' LIMIT 1),
       (SELECT id FROM public.ml_categories LIMIT 1),
       'P-M2-001', '示例商品 - 商家2', 89.00, 80, 80, NOW(), NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM public.ml_products p WHERE p.merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1
);

-- 3.2 插入 SKU（如果没有）
WITH p1 AS (
    SELECT id AS product_id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant1@mall.com') LIMIT 1
), p2 AS (
    SELECT id AS product_id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1
)
INSERT INTO public.ml_product_skus (id, product_id, sku_code, price, stock, created_at, updated_at)
SELECT uuid_generate_v4(), p.product_id, 'SKU-M1-001', 199.00, 50, NOW(), NOW() FROM p1 p
WHERE NOT EXISTS (SELECT 1 FROM public.ml_product_skus s WHERE s.product_id = p.product_id LIMIT 1);

-- 插入商家2 的 SKU（使用内联子查询，确保幂等且避免 CTE 范围问题）
INSERT INTO public.ml_product_skus (id, product_id, sku_code, price, stock, created_at, updated_at)
SELECT uuid_generate_v4(), p.product_id, 'SKU-M2-001', 89.00, 80, NOW(), NOW()
FROM (
        SELECT id AS product_id
        FROM public.ml_products
        WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com' LIMIT 1)
        LIMIT 1
) p
WHERE p.product_id IS NOT NULL
    AND NOT EXISTS (SELECT 1 FROM public.ml_product_skus s WHERE s.product_id = p.product_id LIMIT 1);

-- 4. 插入 3 个订单：两个不同商家各一单 + 一个多商品订单
-- 订单 1: customer1 从 merchant1 购买 1 件
WITH
buyer AS (SELECT id AS user_id FROM public.ak_users WHERE email = 'customer1@mall.com' LIMIT 1),
merchant AS (SELECT id AS merchant_id FROM public.ak_users WHERE email = 'merchant1@mall.com' LIMIT 1),
prod AS (SELECT id AS product_id FROM public.ml_products WHERE merchant_id = (SELECT merchant_id FROM merchant) LIMIT 1),
sku AS (SELECT id AS sku_id, price FROM public.ml_product_skus WHERE product_id = (SELECT product_id FROM prod) LIMIT 1),
ins_order AS (
    INSERT INTO public.ml_orders (id, order_no, user_id, merchant_id, product_amount, discount_amount, shipping_fee, total_amount, paid_amount, shipping_address, order_status, payment_status, shipping_status, created_at, updated_at)
    SELECT uuid_generate_v4(), public.generate_order_no(), b.user_id, m.merchant_id, s.price, 0, 10.00, s.price + 10.00, 0,
        jsonb_build_object('receiver_name','王小明','receiver_phone','13800138003','province','北京市','city','朝阳区','district','望京街道','address_detail','望京SOHO T1座 1201室'),
        1, 1, 1, NOW(), NOW()
    FROM buyer b, merchant m, sku s
    RETURNING id
)
INSERT INTO public.ml_order_items (id, order_id, product_id, sku_id, product_name, sku_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), o.id, p.product_id, s.sku_id, '示例商品 - 商家1', '默认SKU', s.price, 1, s.price * 1, NOW()
FROM ins_order o, prod p, sku s;

-- 创建配送任务 for 订单1
INSERT INTO public.ml_delivery_tasks (id, order_id, driver_id, pickup_address, delivery_address, distance, estimated_time, delivery_fee, status, assigned_at, created_at, updated_at)
SELECT uuid_generate_v4(), o.id, (SELECT id FROM public.ml_delivery_drivers WHERE user_id = (SELECT id FROM public.ak_users WHERE email = 'driver1@mall.com') LIMIT 1),
    jsonb_build_object('address','商家取货点','phone','010-00000001'),
    jsonb_build_object('receiver_name','王小明','receiver_phone','13800138003','address_detail','望京SOHO T1座 1201室'),
    3.5, 20, 5.00, 1, NOW(), NOW(), NOW()
FROM (SELECT id FROM public.ml_orders WHERE id = (SELECT id FROM public.ml_orders ORDER BY created_at DESC LIMIT 1) LIMIT 1) o
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks t WHERE t.order_id = o.id);

-- 订单 2: customer2 从 merchant2 购买 2 件
WITH
buyer2 AS (SELECT id AS user_id FROM public.ak_users WHERE email = 'customer2@mall.com' LIMIT 1),
merchantB AS (SELECT id AS merchant_id FROM public.ak_users WHERE email = 'merchant2@mall.com' LIMIT 1),
prodB AS (SELECT id AS product_id FROM public.ml_products WHERE merchant_id = (SELECT merchant_id FROM merchantB) LIMIT 1),
skuB AS (SELECT id AS sku_id, price FROM public.ml_product_skus WHERE product_id = (SELECT product_id FROM prodB) LIMIT 1),
ins_order2 AS (
    INSERT INTO public.ml_orders (id, order_no, user_id, merchant_id, product_amount, discount_amount, shipping_fee, total_amount, paid_amount, shipping_address, order_status, payment_status, shipping_status, created_at, updated_at)
    SELECT uuid_generate_v4(), public.generate_order_no(), b.user_id, m.merchant_id, s.price * 2, 0, 8.00, s.price * 2 + 8.00, 0,
        jsonb_build_object('receiver_name','李小红','receiver_phone','13800138004','province','北京市','city','海淀区','district','中关村街道','address_detail','中关村大街1号 科技大厦'),
        1, 1, 1, NOW(), NOW()
    FROM buyer2 b, merchantB m, skuB s
    RETURNING id
)
INSERT INTO public.ml_order_items (id, order_id, product_id, sku_id, product_name, sku_name, price, quantity, total_amount, created_at)
SELECT uuid_generate_v4(), o.id, p.product_id, s.sku_id, '示例商品 - 商家2', '默认SKU', s.price, 2, s.price * 2, NOW()
FROM ins_order2 o, prodB p, skuB s;

-- 创建配送任务 for 订单2
INSERT INTO public.ml_delivery_tasks (id, order_id, driver_id, pickup_address, delivery_address, distance, estimated_time, delivery_fee, status, assigned_at, created_at, updated_at)
SELECT uuid_generate_v4(), o.id, (SELECT id FROM public.ml_delivery_drivers WHERE user_id = (SELECT id FROM public.ak_users WHERE email = 'driver1@mall.com') LIMIT 1),
    jsonb_build_object('address','商家取货点','phone','010-00000002'),
    jsonb_build_object('receiver_name','李小红','receiver_phone','13800138004','address_detail','中关村大街1号 科技大厦'),
    6.0, 35, 6.50, 1, NOW(), NOW(), NOW()
FROM (SELECT id FROM public.ml_orders WHERE created_at = (SELECT MAX(created_at) FROM public.ml_orders) LIMIT 1) o
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks t WHERE t.order_id = o.id);

-- 订单 3: customer1 购买商家1 的商品 + 商家2 的商品（跨店多商品示例，示意用）
-- 备注：实际业务可能不允许跨商家单一订单，这里仅作为测试多商品记录演示（如果系统不允许，请忽略）
WITH
buyer3 AS (SELECT id AS user_id FROM public.ak_users WHERE email = 'customer1@mall.com' LIMIT 1),
m1 AS (SELECT id AS merchant1_id FROM public.ak_users WHERE email = 'merchant1@mall.com' LIMIT 1),
m2 AS (SELECT id AS merchant2_id FROM public.ak_users WHERE email = 'merchant2@mall.com' LIMIT 1),
prod1 AS (SELECT id AS product1_id FROM public.ml_products WHERE merchant_id = (SELECT merchant1_id FROM m1) LIMIT 1),
sku1 AS (SELECT id AS sku1_id, price FROM public.ml_product_skus WHERE product_id = (SELECT product1_id FROM prod1) LIMIT 1),
prod2 AS (SELECT id AS product2_id FROM public.ml_products WHERE merchant_id = (SELECT merchant2_id FROM m2) LIMIT 1),
sku2 AS (SELECT id AS sku2_id, price FROM public.ml_product_skus WHERE product_id = (SELECT product2_id FROM prod2) LIMIT 1),
ins_order3 AS (
    INSERT INTO public.ml_orders (id, order_no, user_id, merchant_id, product_amount, discount_amount, shipping_fee, total_amount, paid_amount, shipping_address, order_status, payment_status, shipping_status, created_at, updated_at)
    SELECT uuid_generate_v4(), public.generate_order_no(), b.user_id, (SELECT merchant1_id FROM m1),
        COALESCE(s1.price,0) + COALESCE(s2.price,0), 0, 12.00, COALESCE(s1.price,0)+COALESCE(s2.price,0)+12.00, 0,
        jsonb_build_object('receiver_name','王小明','receiver_phone','13800138003','province','北京市','city','朝阳区','district','望京街道','address_detail','望京SOHO T1座 1201室'),
        1,1,1, NOW(), NOW()
    FROM buyer3 b LEFT JOIN sku1 s1 ON TRUE LEFT JOIN sku2 s2 ON TRUE
    RETURNING id
) 
INSERT INTO public.ml_order_items (id, order_id, product_id, sku_id, product_name, sku_name, price, quantity, total_amount, created_at)
SELECT
    uuid_generate_v4(),
    o.id,
    (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant1@mall.com') LIMIT 1) AS product_id,
    (SELECT id FROM public.ml_product_skus WHERE product_id = (SELECT id FROM pu    SELECT id, email, username, role, auth_id FROM public.ak_users WHERE email = '123@123.com';blic.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant1@mall.com') LIMIT 1) LIMIT 1) AS sku_id,
    '示例商品 - 商家1',
    '默认SKU',
    COALESCE((SELECT price FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant1@mall.com') LIMIT 1) LIMIT 1),0) AS price,
    1,
    COALESCE((SELECT price FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant1@mall.com') LIMIT 1) LIMIT 1),0) AS total_amount,
    NOW()
FROM (
    SELECT id FROM public.ml_orders WHERE created_at = (SELECT MAX(created_at) FROM public.ml_orders) LIMIT 1
) o
WHERE (SELECT id FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant1@mall.com') LIMIT 1) LIMIT 1) IS NOT NULL
ON CONFLICT DO NOTHING;

INSERT INTO public.ml_order_items (id, order_id, product_id, sku_id, product_name, sku_name, price, quantity, total_amount, created_at)
SELECT
    uuid_generate_v4(),
    o.id,
    (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1) AS product_id,
    (SELECT id FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1) LIMIT 1) AS sku_id,
    '示例商品 - 商家2',
    '默认SKU',
    COALESCE((SELECT price FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1) LIMIT 1),0) AS price,
    1,
    COALESCE((SELECT price FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1) LIMIT 1),0) AS total_amount,
    NOW()
FROM (
    SELECT id FROM public.ml_orders WHERE created_at = (SELECT MAX(created_at) FROM public.ml_orders) LIMIT 1
) o
WHERE (SELECT id FROM public.ml_product_skus WHERE product_id = (SELECT id FROM public.ml_products WHERE merchant_id = (SELECT id FROM public.ak_users WHERE email = 'merchant2@mall.com') LIMIT 1) LIMIT 1) IS NOT NULL
ON CONFLICT DO NOTHING;

-- 为订单3 创建配送任务（若存在）
INSERT INTO public.ml_delivery_tasks (id, order_id, driver_id, pickup_address, delivery_address, distance, estimated_time, delivery_fee, status, assigned_at, created_at, updated_at)
SELECT uuid_generate_v4(), o.id, (SELECT id FROM public.ml_delivery_drivers WHERE user_id = (SELECT id FROM public.ak_users WHERE email = 'driver1@mall.com') LIMIT 1),
    jsonb_build_object('address','商家取货点','phone','010-00000003'),
    jsonb_build_object('receiver_name','王小明','receiver_phone','13800138003','address_detail','望京SOHO T1座 1201室'),
    5.0, 30, 7.00, 1, NOW(), NOW(), NOW()
FROM (SELECT id FROM public.ml_orders WHERE created_at = (SELECT MAX(created_at) FROM public.ml_orders) LIMIT 1) o
WHERE NOT EXISTS (SELECT 1 FROM public.ml_delivery_tasks t WHERE t.order_id = o.id);

COMMIT;

-- 执行完成后请在 Supabase SQL Editor 中确认插入结果：
-- SELECT * FROM public.ml_orders ORDER BY created_at DESC LIMIT 10;
-- SELECT * FROM public.ml_order_items ORDER BY created_at DESC LIMIT 20;
-- SELECT * FROM public.ml_delivery_tasks ORDER BY created_at DESC LIMIT 10;
