-- ===================================================================
-- 用途：为已存在的 auth 用户创建 ml_delivery_staff 服务人员档案（兼容 v1/v2）
-- 前提：auth.users 中已有 homecare_worker@test.com
-- ===================================================================

DO $$
DECLARE
    v_uid UUID;
    v_has_v2 BOOLEAN := FALSE;
BEGIN
    -- 1. 通过邮箱找到用户 ID
    SELECT id INTO v_uid FROM auth.users WHERE email = 'homecare_worker@test.com' LIMIT 1;

    IF v_uid IS NULL THEN
        RAISE EXCEPTION 'auth.users 中不存在 homecare_worker@test.com，请先创建该用户';
    END IF;

    -- 2. 确保 ak_users 中有对应记录（role 必须是 delivery）
    INSERT INTO public.ak_users (id, username, email, role, created_at, updated_at)
    VALUES (v_uid, '居家服务员', 'homecare_worker@test.com', 'delivery', NOW(), NOW())
    ON CONFLICT (id) DO UPDATE SET
        username = EXCLUDED.username,
        role = EXCLUDED.role,
        updated_at = NOW();

    RAISE NOTICE '✓ ak_users 已就绪，uid: %', v_uid;

    -- 3. 探测 ml_delivery_staff 是否为 v2 结构（是否有 online_status 字段）
    SELECT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'ml_delivery_staff'
          AND column_name = 'online_status'
    ) INTO v_has_v2;

    -- 4. 根据表结构版本执行对应插入
    IF v_has_v2 THEN
        -- v2 结构（含 online_status, certificate_status, staff_no 等）
        INSERT INTO public.ml_delivery_staff (
            id, uid, nickname, avatar, phone,
            status, is_active,
            staff_no, online_status, certificate_status,
            certificate_expire_at, service_area, skills,
            created_at, updated_at
        ) VALUES (
            gen_random_uuid(), v_uid, '居家服务员',
            'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare',
            '13800138000',
            1, TRUE,
            'HC' || EXTRACT(YEAR FROM NOW()) || LPAD(FLOOR(RANDOM() * 10000)::TEXT, 4, '0'),
            'resting', 'valid',
            (NOW() + INTERVAL '1 year')::DATE,
            '北京市朝阳区',
            '["基础护理", "康复训练", "上门照护"]'::jsonb,
            NOW(), NOW()
        )
        ON CONFLICT (uid) WHERE deleted_at IS NULL DO UPDATE SET
            nickname = EXCLUDED.nickname,
            status = EXCLUDED.status,
            is_active = EXCLUDED.is_active,
            updated_at = NOW();

        RAISE NOTICE '✓ ml_delivery_staff (v2) 档案已创建/更新';
    ELSE
        -- v1 结构（仅基础字段）
        INSERT INTO public.ml_delivery_staff (
            id, uid, nickname, avatar, phone,
            status, is_active,
            created_at, updated_at
        ) VALUES (
            gen_random_uuid(), v_uid, '居家服务员',
            'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare',
            '13800138000',
            1, TRUE,
            NOW(), NOW()
        )
        ON CONFLICT (uid) DO UPDATE SET
            nickname = EXCLUDED.nickname,
            status = EXCLUDED.status,
            is_active = EXCLUDED.is_active,
            updated_at = NOW();

        RAISE NOTICE '✓ ml_delivery_staff (v1) 档案已创建/更新';
    END IF;

    RAISE NOTICE '============================================';
    RAISE NOTICE '建档完成！请重新编译小程序后登录测试。';
    RAISE NOTICE '============================================';

END $$;
