-- =====================================================================================
-- RPC: rpc_admin_kefu_account_save
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：新增或更新客服账号
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_account_save(
    p_id UUID DEFAULT NULL,
    p_user_id UUID DEFAULT NULL,
    p_nickname TEXT DEFAULT NULL,
    p_avatar TEXT DEFAULT NULL,
    p_status SMALLINT DEFAULT 1
)
RETURNS UUID
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_id UUID;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 新增
    IF p_id IS NULL THEN
        IF p_user_id IS NULL OR p_nickname IS NULL THEN
            RAISE EXCEPTION 'Missing required fields';
        END IF;

        INSERT INTO public.ml_kefu_accounts (
            user_id, nickname, avatar, status
        ) VALUES (
            p_user_id, p_nickname, p_avatar, p_status
        ) RETURNING id INTO v_id;
    ELSE
        -- 3. 更新
        UPDATE public.ml_kefu_accounts
        SET 
            nickname = COALESCE(p_nickname, nickname),
            avatar = COALESCE(p_avatar, avatar),
            status = COALESCE(p_status, status),
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

        IF v_id IS NULL THEN
            RAISE EXCEPTION 'Account not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;
