-- =============================================
-- 配送效率分析 - 测试数据插入脚本
-- 说明：
-- - 用于生成配送员 + 近 30 天配送任务（已送达），便于配送效率分析页面展示趋势与排行。
-- - 可重复执行：配送员按 real_name 唯一键去重；任务默认会持续累加。
-- - 如需每次重置数据，请取消 TRUNCATE 注释。
-- =============================================

-- For a clean test, you can uncomment these lines to clear old data.
-- TRUNCATE public.ml_delivery_tasks, public.ml_delivery_drivers RESTART IDENTITY;

-- 1) Insert a pool of drivers.
-- ON CONFLICT ensures this is safe to run multiple times.
INSERT INTO public.ml_delivery_drivers (real_name, work_status, rating_avg, rating_count)
VALUES
  ('张配送', 1, 4.8, 32),
  ('李骑手', 1, 4.5, 20),
  ('王师傅', 2, 4.9, 150),
  ('赵快递', 3, 4.7, 88),
  ('刘哥', 1, 4.6, 54),
  ('新人小陈', 1, 3.9, 12)
ON CONFLICT (real_name) DO NOTHING;


-- 2) Generate tasks for the last 30 days.
DO $$
DECLARE
    driver_ids UUID[];
    d_id UUID;
    i INT;
    j INT;
    num_tasks INT;
    assigned_time TIMESTAMPTZ;
    delivery_duration INT; -- in minutes
BEGIN
    -- Get all driver IDs into an array
    SELECT array_agg(id) INTO driver_ids FROM public.ml_delivery_drivers;

    IF array_length(driver_ids, 1) IS NULL THEN
        RAISE NOTICE 'No drivers found, skipping task generation.';
        RETURN;
    END IF;

    -- Loop for the last 30 days
    FOR i IN 0..29 LOOP
        -- Create a random number of tasks for each day
        num_tasks := floor(random() * 10 + 5)::INT; -- 5 to 14 tasks per day
        FOR j IN 1..num_tasks LOOP
            -- Pick a random driver
            d_id := driver_ids[floor(random() * array_length(driver_ids, 1) + 1)];

            -- Generate a random time within the day (from 8am to 10pm)
            assigned_time := (NOW() - (i || ' days')::INTERVAL)::date
              + '8 hours'::interval
              + (floor(random() * 14 * 60) || ' minutes')::interval;

            -- Generate random delivery duration (10 to 50 minutes)
            delivery_duration := floor(random() * 41 + 10);

            INSERT INTO public.ml_delivery_tasks (order_id, driver_id, status, assigned_at, delivered_at, delivery_fee)
            VALUES (
              gen_random_uuid(), -- Generate a unique order_id for each task
              d_id,
              5, -- Status 'Delivered'
              assigned_time,
              assigned_time + (delivery_duration || ' minutes')::INTERVAL,
              floor(random() * 8 + 3) -- Fee between 3 and 10
            );
        END LOOP;
    END LOOP;
END;
$$;
