-- ===================================================================
-- 用途：为已存在的 auth 用户创建 ak_users + ml_delivery_staff 档案
-- 特点：自动探测 ak_users 表结构（有 auth_id 则插 auth_id，无则插 id）
-- ===================================================================

DO $$
DECLARE
    v_auth_id UUID;
    v_ak_user_id UUID;
    v_has_auth_id BOOLEAN := FALSE;
    v_has_phone BOOLEAN := FALSE;
    v_has_avatar_url BOOLEAN := FALSE;
    v_has_status BOOLEAN := FALSE;
    v_has_registration_source BOOLEAN := FALSE;
    v_has_v2 BOOLEAN := FALSE;
    v_email TEXT := 'homecare_worker@test.com';
    v_nickname TEXT := '居家服务员';
    v_phone TEXT := '13800138000';
BEGIN
    -- 1. 获取 auth.users.id
    SELECT id INTO v_auth_id FROM auth.users WHERE email = v_email LIMIT 1;
    IF v_auth_id IS NULL THEN
        RAISE EXCEPTION 'auth.users 中不存在 %', v_email;
    END IF;

    -- 2. 探测 ak_users 表结构
    SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ak_users' AND column_name = 'auth_id')
        INTO v_has_auth_id;
    SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ak_users' AND column_name = 'phone')
        INTO v_has_phone;
    SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ak_users' AND column_name = 'avatar_url')
        INTO v_has_avatar_url;
    SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ak_users' AND column_name = 'status')
        INTO v_has_status;
    SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ak_users' AND column_name = 'registration_source')
        INTO v_has_registration_source;

    RAISE NOTICE 'ak_users 结构探测: auth_id=%, phone=%, avatar_url=%, status=%, registration_source=%',
        v_has_auth_id, v_has_phone, v_has_avatar_url, v_has_status, v_has_registration_source;

    -- 3. 插入 ak_users（动态字段）
    IF v_has_auth_id THEN
        -- 有 auth_id 字段：id 用 gen_random_uuid，auth_id 关联 auth.users.id
        INSERT INTO public.ak_users (
            id, auth_id, username, email, role,
            phone, avatar_url, status, registration_source,
            created_at, updated_at
        ) VALUES (
            gen_random_uuid(), v_auth_id, v_nickname, v_email, 'delivery',
            v_phone, 'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare', 'active', 'web',
            NOW(), NOW()
        )
        ON CONFLICT (auth_id) DO UPDATE SET
            username = EXCLUDED.username,
            email = EXCLUDED.email,
            role = EXCLUDED.role,
            phone = EXCLUDED.phone,
            avatar_url = EXCLUDED.avatar_url,
            status = EXCLUDED.status,
            updated_at = NOW()
        RETURNING id INTO v_ak_user_id;

        RAISE NOTICE '✓ ak_users 已插入（含 auth_id），业务主键 id: %', v_ak_user_id;
    ELSE
        -- 无 auth_id 字段：id 直接等于 auth.users.id
        INSERT INTO public.ak_users (
            id, username, email, role,
            created_at, updated_at
        ) VALUES (
            v_auth_id, v_nickname, v_email, 'delivery',
            NOW(), NOW()
        )
        ON CONFLICT (id) DO UPDATE SET
            username = EXCLUDED.username,
            email = EXCLUDED.email,
            role = EXCLUDED.role,
            updated_at = NOW()
        RETURNING id INTO v_ak_user_id;

        RAISE NOTICE '✓ ak_users 已插入（id = auth_id），id: %', v_ak_user_id;
    END IF;

    -- 4. 探测 ml_delivery_staff v2 字段
    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;

    -- 5. 插入 ml_delivery_staff（uid 必须等于 ak_users.id / ak_users 业务主键）
    IF v_has_v2 THEN
        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_ak_user_id,   -- 关键：必须是 ak_users 的业务主键 id
            v_nickname,
            'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare',
            v_phone,
            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
        INSERT INTO public.ml_delivery_staff (
            id, uid, nickname, avatar, phone,
            status, is_active, created_at, updated_at
        ) VALUES (
            gen_random_uuid(),
            v_ak_user_id,   -- 关键：必须是 ak_users 的业务主键 id
            v_nickname,
            'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare',
            v_phone,
            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 'auth.users.id: %', v_auth_id;
    RAISE NOTICE 'ak_users.id: %', v_ak_user_id;
    RAISE NOTICE 'ml_delivery_staff.uid: %', v_ak_user_id;
    RAISE NOTICE '============================================';

END $$;
