-- RPC: rpc_admin_save_delivery_staff
-- 管理端新增或更新配送员信息

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

    -- 2. 参数校验
    IF p_nickname IS NULL OR p_phone IS NULL THEN
        RAISE EXCEPTION 'Missing required fields: nickname or phone';
    END IF;

    -- 3. 新增或更新
    IF p_id IS NULL THEN
        INSERT INTO public.ml_delivery_staff (
            nickname, avatar, phone, status
        ) VALUES (
            p_nickname, p_avatar, p_phone, p_status
        ) RETURNING id INTO v_id;
    ELSE
        UPDATE public.ml_delivery_staff
        SET 
            nickname = COALESCE(p_nickname, nickname),
            avatar = COALESCE(p_avatar, avatar),
            phone = COALESCE(p_phone, phone),
            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 'Delivery staff not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_save_delivery_staff(UUID, TEXT, TEXT, TEXT, SMALLINT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_save_delivery_staff(UUID, TEXT, TEXT, TEXT, SMALLINT) TO authenticated;
