-- =====================================================================================
-- 脚本：创建居家服务员测试账号及完整档案（一站式 SQL）
-- 用途：为 delivery 端登录提供真实的服务人员档案
-- 执行环境：Supabase SQL Editor（需 postgres/superuser 权限）
-- 对应前端配置：医疗-delivery/ak/config.uts
--   - SUPA_URL: http://119.146.131.237:9126
--   - 测试账号: homecare_worker@test.com / Homecare123!
-- =====================================================================================

-- 0. 确保 pgcrypto 扩展可用（用于 bcrypt 密码哈希）
CREATE EXTENSION IF NOT EXISTS pgcrypto;

DO $$
DECLARE
    v_auth_id UUID;
    v_instance_id UUID;
    v_email TEXT := 'homecare_worker@test.com';
    v_password TEXT := 'Homecare123!';
    v_nickname TEXT := '居家服务员';
    v_phone TEXT := '13800138000';
BEGIN
    -- -------------------------------------------------------------------------
    -- 步骤 1：获取 instance_id（自托管 Supabase 通常只有一个 instance）
    -- -------------------------------------------------------------------------
    SELECT id INTO v_instance_id FROM auth.instances LIMIT 1;
    IF v_instance_id IS NULL THEN
        v_instance_id := '00000000-0000-0000-0000-000000000000'::UUID;
    END IF;

    -- -------------------------------------------------------------------------
    -- 步骤 2：创建/更新 auth.users（Supabase Auth 核心用户表）
    -- 使用 crypt(..., gen_salt('bf')) 生成 bcrypt 哈希，与 gotrue 兼容
    -- -------------------------------------------------------------------------
    INSERT INTO auth.users (
        instance_id,
        id,
        aud,
        role,
        email,
        encrypted_password,
        email_confirmed_at,
        confirmation_sent_at,
        recovery_sent_at,
        email_change_sent_at,
        new_email,
        invited_at,
        confirmation_token,
        recovery_token,
        email_change_token_new,
        email_change_token_current,
        email_change,
        email_change_confirm_status,
        banned_until,
        reauthentication_token,
        reauthentication_sent_at,
        is_super_admin,
        created_at,
        updated_at,
        phone,
        phone_confirmed_at,
        phone_change,
        phone_change_token,
        phone_change_sent_at,
        confirmed_at,
        raw_app_meta_data,
        raw_user_meta_data,
        is_sso_user,
        deleted_at,
        is_anonymous
    ) VALUES (
        v_instance_id,
        gen_random_uuid(),
        'authenticated',
        'authenticated',
        v_email,
        crypt(v_password, gen_salt('bf')),
        NOW(),
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        '',
        '',
        '',
        '',
        '',
        0,
        NULL,
        '',
        NULL,
        FALSE,
        NOW(),
        NOW(),
        NULL,
        NULL,
        NULL,
        '',
        NULL,
        NOW(),
        '{"provider":"email","providers":["email"]}'::jsonb,
        '{"name":"居家服务员","role":"delivery","nickname":"居家服务员"}'::jsonb,
        FALSE,
        NULL,
        FALSE
    )
    ON CONFLICT (email) DO UPDATE SET
        encrypted_password = crypt(v_password, gen_salt('bf')),
        email_confirmed_at = COALESCE(auth.users.email_confirmed_at, NOW()),
        confirmed_at = COALESCE(auth.users.confirmed_at, NOW()),
        updated_at = NOW(),
        raw_user_meta_data = '{"name":"居家服务员","role":"delivery","nickname":"居家服务员"}'::jsonb,
        deleted_at = NULL,
        is_anonymous = FALSE;

    -- 获取刚创建/更新的用户 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 插入失败，请检查权限或表结构';
    END IF;

    RAISE NOTICE '✓ auth.users 已创建/更新: % (ID: %)', v_email, v_auth_id;

    -- -------------------------------------------------------------------------
    -- 步骤 3：创建 auth.identities（Supabase Auth 身份表，某些版本必需）
    -- -------------------------------------------------------------------------
    INSERT INTO auth.identities (
        id,
        user_id,
        identity_data,
        provider,
        created_at,
        updated_at
    ) VALUES (
        v_auth_id::TEXT,
        v_auth_id,
        jsonb_build_object('sub', v_auth_id::TEXT, 'email', v_email),
        'email',
        NOW(),
        NOW()
    )
    ON CONFLICT (id) DO UPDATE SET
        identity_data = jsonb_build_object('sub', v_auth_id::TEXT, 'email', v_email),
        updated_at = NOW();

    RAISE NOTICE '✓ auth.identities 已创建/更新';

    -- -------------------------------------------------------------------------
    -- 步骤 4：创建 public.ak_users（业务用户资料表）
    -- -------------------------------------------------------------------------
    INSERT INTO public.ak_users (
        id,
        username,
        email,
        gender,
        birthday,
        height_cm,
        weight_kg,
        bio,
        avatar_url,
        preferred_language,
        health_goal,
        service_address,
        emergency_contact,
        chronic_notes,
        care_preference,
        role,
        school_id,
        grade_id,
        class_id,
        created_at,
        updated_at
    ) VALUES (
        v_auth_id,
        v_nickname,
        v_email,
        'unknown',
        NULL,
        0,
        0,
        '居家养老护理员，具备基础护理和康复训练资质',
        'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare',
        'zh-CN',
        '',
        '',
        '',
        '',
        '',
        'delivery',
        '',
        '',
        '',
        NOW(),
        NOW()
    )
    ON CONFLICT (id) DO UPDATE SET
        username = EXCLUDED.username,
        email = EXCLUDED.email,
        role = EXCLUDED.role,
        bio = EXCLUDED.bio,
        avatar_url = EXCLUDED.avatar_url,
        updated_at = NOW();

    RAISE NOTICE '✓ public.ak_users 已插入/更新';

    -- -------------------------------------------------------------------------
    -- 步骤 5：创建 public.ml_delivery_staff（服务人员档案表）
    -- -------------------------------------------------------------------------
    INSERT INTO public.ml_delivery_staff (
        id,
        uid,
        nickname,
        avatar,
        phone,
        status,
        is_active,
        station_id,
        staff_no,
        online_status,
        certificate_status,
        certificate_expire_at,
        service_area,
        skills,
        created_at,
        updated_at
    ) VALUES (
        gen_random_uuid(),
        v_auth_id,
        v_nickname,
        'https://api.dicebear.com/7.x/avataaars/svg?seed=homecare',
        v_phone,
        1,                              -- 状态: 1-启用
        TRUE,                           -- 是否激活
        NULL,                           -- 所属站点（可选）
        '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,
        phone = EXCLUDED.phone,
        status = EXCLUDED.status,
        is_active = EXCLUDED.is_active,
        online_status = EXCLUDED.online_status,
        certificate_status = EXCLUDED.certificate_status,
        service_area = EXCLUDED.service_area,
        skills = EXCLUDED.skills,
        updated_at = NOW();

    RAISE NOTICE '✓ public.ml_delivery_staff 已插入/更新';

    -- -------------------------------------------------------------------------
    -- 完成
    -- -------------------------------------------------------------------------
    RAISE NOTICE '============================================';
    RAISE NOTICE '居家服务员账号初始化完成！';
    RAISE NOTICE '邮箱: %', v_email;
    RAISE NOTICE '密码: %', v_password;
    RAISE NOTICE '用户ID: %', v_auth_id;
    RAISE NOTICE 'SUPA_URL: http://119.146.131.237:9126';
    RAISE NOTICE '============================================';

END $$;
